$('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
Don't use eval
, use a 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]);
});
Instead of using eval
, - better change you data structures:
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]);
});
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]();
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]());
});
I think it would be easier to write a new function with a switch. I can't recommend using eval.
$('a').live('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, eval('marker' + id));
});
Notes:
eval
is deprecated, You should look for a better design. live
... You should use on
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.