[英]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 variable ID?如何将数字 2 动态更改为变量 ID?
Thanks for any help谢谢你的帮助
Don't use eval
, use a hash:不要使用
eval
,使用 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:与其使用
eval
,不如更改数据结构:
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.为了在 function 名称中使用动态名称,您可以 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.我认为用开关写一个新的 function 会更容易。 I can't recommend using eval.
我不推荐使用 eval。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.