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
精彩评论