Is there a way to call methods by their name in jQuery? For example:
var condition = true;
$('div').execute(condition ? 'show':'hide');
asked Jul 6, 2011 at 11:33
Dziamid
11.7k13 gold badges73 silver badges108 bronze badges
-
What is it you are trying to do? It may be that there is a better solution not involving dictionary based access of methods.Spycho– Spycho2011年07月06日 11:40:46 +00:00Commented Jul 6, 2011 at 11:40
2 Answers 2
Yes, use the []notation to access properties of the jQuery object (rather than literal ones using .):
$('div')[condition ? 'show' : 'hide']();
You can also do:
$('div').toggle(condition);
http://www.jibbering.com/faq/faq_notes/square_brackets.html
Edit: Just in case you prefer your own style of coding, you could add this:
$.fn.execute = function(a) {
return this[a].apply(this, [].slice.call(arguments, 1));
}
Then you can do like:
$('div').execute(condition ? 'show' : 'hide');
or
$('div').execute(condition ? 'keydown' : 'keyup', function() {...});
answered Jul 6, 2011 at 11:33
pimvdb
155k80 gold badges313 silver badges358 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
pimvdb
@Dziamid: I use
.toggle mostly, because it's clearer to read.Javascript objects are basically dictionaries.
var condition = true;
$('div')[condition ? 'show':'hide']();
answered Jul 6, 2011 at 11:34
fulmicoton
16.1k10 gold badges56 silver badges74 bronze badges
Comments
lang-js