Dynamically change function name in javascript
$('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 a variable id?
Thanks for any help
+3
zugrina
source
to share
5 answers
$('a').live('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, eval('marker' + id));
});
LIVE DEMO
Notes:
-
eval
is outdated, you should be looking for a better design. - since
live
... you should use insteadon
.
-2
gdoron
source
to share
Don't use eval
, use hash:
var markers = {
"key1": function(){},
"key2": function(){},
"key3": function(){}
};
$('a').live('click',function(e){
e.preventDefault();
var id = this.id; //Use this.id instead of attr
infowindow2.open(map, markers[id]);
});
+10
Dennis
source
to share
Instead of using eval
, it is better to change the data structure:
var markers = {
'1': function () { doStuff(); },
'2': function () { doOtherStuff(); },
}
$('a').live('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, markers[id]);
});
+6
c69
source
to share
EVAL should always be the last option
To use dynamic name in function names, you can use Windows object.
Here's an example:
var id = '2';
function map2() {
alert('me called');
}
window["map"+id]();
Demo
Your use would be something like this
$('a').on('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, window['map'+id]());
});
0
Starx
source
to share
I think it would be easier to write a new function using a switch. I cannot recommend using eval.
0
Eirinn
source
to share