Is there a way to call methods by their name in jQuery? For example:
var condition = true;
$('d开发者_JAVA技巧iv').execute(condition ? 'show':'hide');
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://api.jquery.com/toggle/
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() {...});
Javascript objects are basically dictionaries.
var condition = true;
$('div')[condition ? 'show':'hide']();
精彩评论