简体   繁体   English

在 javascript 中动态更改 function 名称

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

EVAL should always be the last option EVAL 应该始终是最后一个选项

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

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

I think it would be easier to write a new function with a switch.我认为用开关写一个新的 function 会更容易。 I can't recommend using eval.我不推荐使用 eval。

$('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. eval已弃用,您应该寻找更好的设计。
  • so as live ... You should use on instead. so as live ... 你应该使用on代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM