开发者

jQuery use variable as event?

Is there a way in jQuery or javascript to trigger a variable string as an even开发者_运维百科t?

ex.

if (a == b) {
    x = "$('div').hide()";
} else {
    x = "$('div').show()";
}

*trigger x event here*

Ignore the fact that this isn't the correct way to do it.. It is only an example to make the question easier to understand.

Thanks


You could use the eval function:

var x = '';
if (a == b) {
    x = "$('div').hide()";
} else {
    x = "$('div').show()";
}

eval(x);

Also you could simplify your code like this using the .toggle() method which obviously is a far better solution:

$('div').toggle(a == b);


if (a == b) {
    action = "hide";
} else {
    action = "show";
}

$('div')[action]();

Or you can use jQuery.toggle

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜