Reputation: 149
I need to run a function with a part dynamic variable in it's name.
The function to run:
$.element_gallery = function(state){}
The code that's calling it:
var name = "gallery";
window["$.element_"+name]('refresh');
This method seems to work with traditional Javascript functions but not with a jQuery function. Is there a way to run this without using eval()
and without changing the function name?
Upvotes: 0
Views: 53
Reputation: 38345
When you do window["$.foo"]
it's looking for a property on the window object that's called $.foo
. However, if you're using a jQuery function it's stored in the jQuery (or $
) property of the window
object, so the actual location of the function you want is window.$["foo"]. Change your code to:
var name = "gallery";
window.$["element_"+name]('refresh');
Or, since you can access global variables without specifying window.
, just:
var name = "gallery";
$[".element_"+name]('refresh');
Upvotes: 1