Calling A Jquery Function Named In A Variable
I have several jQuery function like function setOne(); setTwo(); setThree(); and a variable var number that values respectively 'one', 'two', 'three'. How can I call function 'set
Solution 1:
If you have your function in the global scope (on the window object) you can do:
// calls function setOne, setTwo, ... depending on number.
window["set" + number]();
And using eval
will allow you to run functions in local scope:
eval("set" + number + "()");
When is JavaScript's eval()
not evil?
Solution 2:
Create a name -> function
map:
var funcs = {
'one': setOne,
'two': setTwo
/*...*/
};
Then you call the function with:
funcs[number]();
Solution 3:
If the variable details the actual name of the JQuery function and you want to apply the function to a DOM element like 'body', you can do the following:
$('body')['function-name']('params');
Solution 4:
Provided your functions are in the global scope, try:
functionsetOne() {
console.log('setOne called');
}
functionsetTwo() {
console.log('setTwo called');
}
functionsetThree() {
console.log('setThree called');
}
varnumber, funcName;
number = 'one';
funcName = 'set' + number.charAt(0).toUpperCase() + number.slice(1);
window[funcName](); // output: setOne callednumber = 'two';
funcName = 'set' + number.charAt(0).toUpperCase() + number.slice(1);
window[funcName](); // output: setTwo callednumber = 'three';
funcName = 'set' + number.charAt(0).toUpperCase() + number.slice(1);
window[funcName](); // output: setThree called
Solution 5:
As simple as this is:
functionhello(){
alert("hello");
}
var str = "hello";
eval(str+"()");
Post a Comment for "Calling A Jquery Function Named In A Variable"