我想用一个对象启动jquery函数“init”。该对象是预定义的
name={a:'d',b:'e',c:'f'}
。对象的名称是我单击的 svg-rect-Object 中的 html-id。
这就是我所拥有的。问题是,调用“nameofrect”时返回的是字符串而不是对象。我能做什么?
$(document).on('click', '.some-svg-rect', function () {
var nameofrect = ((this.id).slice(1)).toLowerCase(); `//normal id = 'r'+somename`
init(nameofrect);
});
最佳答案
这是你可以做的。
var names = {
name1: {a:'d',b:'e',c:'f'}
, name2: {} //etc
}
var nameObj = names[((this.id).slice(1)).toLowerCase()] //this is the object you wanted
基本上,您询问的是通过字符串名称引用全局变量。 Is there a way to access a javascript variable using a string that contains the name of the variable?
您可以只使用 window
变量而不创建 names
对象,但我不建议这样做。 (Get global variable dynamically by name string in JavaScript)
关于jquery - 我如何从随机字符串中描述一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31680101/