Reputation: 7121
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
Reputation: 27022
You can use bracket notation:
function abc() {
//...
}
var func = 'abc';
window[func](); //calls abc()
Upvotes: 4
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