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
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]());
});