0

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.

1
  • Can be done with eval() But remember, eval = evil.. Commented May 27, 2014 at 11:36

2 Answers 2

1

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];
Sign up to request clarification or add additional context in comments.

3 Comments

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.
no... this wont execute the function...
Oh wow, your added section "or create a array/object of functions." works like a charm bro!! Thanxxxx alot :D
-1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.