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.
we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; }; if we simply call this function, nothing will be printed, although nothing is wrong with the writing of the function itself.
In order to access a jQUery function from a JavaScript function, you can declare a variable and assign it to a jQuery function. Finally, just call it from a JavaScript function. In this way you can call a jQuery function from JavaScript.
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.
In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.
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?
Create a name -> function
map:
var funcs = { 'one': setOne, 'two': setTwo /*...*/ };
Then you call the function with:
funcs[number]();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With