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 "setOne()" when number values "one", function "setTwo" when number values "two" and so on...?
Thank you so much in advance. Any help will be apreciated.
-
1Looks like normal JavaScript functions to me.Felix Kling– Felix Kling2011年12月21日 10:28:22 +00:00Commented Dec 21, 2011 at 10:28
7 Answers 7
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 + "()");
5 Comments
this["set" + number](); would not work. Only if setX is a property of whatever this refers to, but not if setX is a local variable.number is exactly as bobighorus describes (e.g. one, two, three) then this will give an error, as setone != setOne?!Create a name -> function map:
var funcs = {
'one': setOne,
'two': setTwo
/*...*/
};
Then you call the function with:
funcs[number]();
7 Comments
function setOne() {...}; or funcs['one'] = function() {...}; should not make a big difference. The advantage is that your code has a cleaner structure and is easier to understand.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');
Comments
Provided your functions are in the global scope, try:
function setOne() {
console.log('setOne called');
}
function setTwo() {
console.log('setTwo called');
}
function setThree() {
console.log('setThree called');
}
var number, funcName;
number = 'one';
funcName = 'set' + number.charAt(0).toUpperCase() + number.slice(1);
window[funcName](); // output: setOne called
number = 'two';
funcName = 'set' + number.charAt(0).toUpperCase() + number.slice(1);
window[funcName](); // output: setTwo called
number = 'three';
funcName = 'set' + number.charAt(0).toUpperCase() + number.slice(1);
window[funcName](); // output: setThree called
Comments
As simple as this is:
function hello(){
alert("hello");
}
var str = "hello";
eval(str+"()");
2 Comments
var str = "One"; eval("set" + str + "()"); for your example. You can even set named parameters this way... eval("set" + str + "(parameterName)");Why do you have three functions for that?
var number;
function setNumber(n) {
number = n;
}
setNumber(1) will set number to 1
setNumber(2) will set number to 2
ect
1 Comment
Further to @Andreas answer, the following illustrates the approach when not using a global.
Make a variable that holds a set of functions:
var callbacks = {
setOne: function(params) {
// ...
},
setTwo: function(params) {
// ...
},
};
Then if you have a variable holding the function name, you can do:
var number = "Two";
callbacks["set" + number](params);