April 6, 2012

dynamically change function name in javascript

Question by zugrina

$('a').live('click',function(e){
    e.preventDefault();
    var id = $(this).attr('id');
    infowindow2.open(map, marker2); // I need instead of 2 to print the value of variable id
});

How can I dynamically change the number 2 to variable ID ?

Thanks for any help

Answer by gdoron

$('a').live('click',function(e){
    e.preventDefault();
    var id = $(this).attr('id');
    infowindow2.open(map, eval('marker' + id)); 
});

LIVE DEMO

Notes:

  • eval is deprecated, You should look for a better design.
  • so as live… You should use on instead.

Answer by Starx

EVAL should always be the last option

In order use dynamic name in a function names you can windows object.

Here is an Example:

var id = '2';
function map2() {
    alert('me called');
}
window["map"+id]();

Demo

Your Usage would be something like this

$('a').on('click',function(e){
    e.preventDefault();
    var id = $(this).attr('id');
    infowindow2.open(map, window['map'+id]()); 
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!