What's the simplest way to call a string method with jquery?
1 Answer
If I understand your question correctly, you want to call a method whose name is stored in a string.
If that's the case, you should use square bracket notation instead of (not in addition to) dot notation, and delimit the literal string with quotes:
$["STRINGVALUE"]();
You can also use the variable you defined initially, without quotes:
$[myFunction]();
4 Comments
Prusprus
May this error be outdated? I've tried it, but it doesn't seem to work. Have gotten it working with eval(STRINGVALUE+'()').
Frédéric Hamidi
@user, it looks like your problem is not the same. You want to call a function named
STRINGVALUE, but cept0 wants to invoke a jQuery method named STRINGVALUE.Prusprus
A function being a user defined function, while a jQuery method is a function defined within the $. namespace?
Frédéric Hamidi
@user, more or less, yes. Technically,
$.fn also comes into play for jQuery methods, but in this particular case the questioner indeed wants to call a method exposed by the $ object directly (such methods are akin to static methods in other languages).