I have function name in a var,
var i = 2; // iteration
var fname = 'myFunction' + i; // looks like myFunction2()
now i want to assign this function on element's event. i.e.
var elem = document.getElementById('e');
elem.onclick = fname;
It doesn't work. JS take function name as 'fname()' not the string inside it 'myFunction2()'
A little help would be appriciated,
Thanks in advance.
asked May 27, 2014 at 11:31
Ali Nawaz Hiraj
1221 silver badge6 bronze badges
-
Can be done with eval() But remember, eval = evil..Ron van der Heijden– Ron van der Heijden2014年05月27日 11:36:40 +00:00Commented May 27, 2014 at 11:36
2 Answers 2
You can do this
window['myFunction' + i]
or create a array/object of functions.
var i = 2; // iteration
var fname = 'myFunction' + i; // looks like myFunction2()
var elem = document.getElementById('e');
elem.onclick = window[fname];
answered May 27, 2014 at 11:33
cocco
16.8k7 gold badges65 silver badges77 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Ali Nawaz Hiraj
Thanks, but this will execute the function right away, am i right? i want the function to be assigned to element 'e'. when mouse clicked on element 'e' then function invoked.
cocco
no... this wont execute the function...
Ali Nawaz Hiraj
Oh wow, your added section "or create a array/object of functions." works like a charm bro!! Thanxxxx alot :D
Check these answers: Javascript - Variable in function name, possible? and Use JavaScript variable as function name?
What you attempt is to assign a string (variable) on an event.
Comments
default