Alon Shmiel
Alon Shmiel

Reputation: 7121

call a function that it's name is like a given string

I have an array of size 2: [3,8].

I want to add onclick for any id that I have by the following:

instead of: $("#a1").click(function(){ a3(); });, I want to do something like:

var a = "a" + arr[0].toString + "();"; // 'a = a3();'

$("#a1").click(function(){ a });

there is an option to call a function by a string?

in other words, I have a string: var func = "abc";

how can I call the func: abc(); by the string of func?

any help appreciated!

Upvotes: 0

Views: 51

Answers (2)

Jason P
Jason P

Reputation: 27022

You can use bracket notation:

function abc() {
   //...
}

var func = 'abc';

window[func](); //calls abc()

Upvotes: 4

Dark Falcon
Dark Falcon

Reputation: 44201

This can be done with []. Here is a solution which should work at any scope:

function a1() {alert('a1');}
var context = this;
$("#a1").click(function(){ context[this.id](); });

Upvotes: 1

Related Questions