开发者

jQuery: execute method from string

开发者 https://www.devze.com 2023-03-17 11:24 出处:网络
Is there a way to call methods by their name in jQuery? For example: var condition = true; $(\'d开发者_JAVA技巧iv\').execute(condition ? \'show\':\'hide\');

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']();
0

精彩评论

暂无评论...
验证码 换一张
取 消