如何从随机字符串中描述对象?

时间:2015-07-28 15:00:33

标签: jquery string object svg reference

我想用Object启动jquery-function“init”。对象是预定义的,如

name={a:'d',b:'e',c:'f'}     

。 Object的名称是我单击的svg-rect-Object中的html-id。

这就是我所拥有的。问题是,调用时“nameofrect”会返回String而不是Object。我该怎么办?

$(document).on('click', '.some-svg-rect', function () {
        var nameofrect = ((this.id).slice(1)).toLowerCase(); `//normal id = 'r'+somename`
        init(nameofrect);
    });

1 个答案:

答案 0 :(得分:0)

Here's what you could do.

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

You were asking about referencing a global variable by its string name, basically. Is there a way to access a javascript variable using a string that contains the name of the variable?

You can just use the window variable without making the names object but I don't recommend that. (Get global variable dynamically by name string in JavaScript)