Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling a jQuery function named in a variable

Tags:

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.

like image 914
bobighorus Avatar asked Dec 21 '11 10:12

bobighorus


People also ask

How do you call a function inside a variable?

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.

Can we call jQuery function in JavaScript?

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.

How do you call a function variable in 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.

What does $() stand for in jQuery?

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.


2 Answers

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?

like image 174
Andreas Louv Avatar answered Sep 21 '22 16:09

Andreas Louv


Create a name -> function map:

var funcs = {     'one': setOne,     'two': setTwo     /*...*/ }; 

Then you call the function with:

funcs[number](); 
like image 22
Felix Kling Avatar answered Sep 18 '22 16:09

Felix Kling