jquery - 我如何从随机字符串中描述一个对象?

标签 jquery string object svg reference

我想用一个对象启动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/

相关文章:

php - 如果是 URL 的一部分,如何忽略正则表达式?

ruby-on-rails - 在 Rails 中合并实例变量(将数据从 Controller 传递到 View )的最佳方法是什么?

WPF:如何将对象绑定(bind)到组合框

jquery - 具有视差、最大宽度技巧的流体图像无法按预期工作

javascript - jQuery ajax 未捕获类型错误 : Illegal invocation

javascript - 添加一个元素到页面。比拖动它

php - 从php中的字符串中提取字符

javascript - 未捕获的语法错误 : Unexpected token ILLEGAL - A simple string syntactically wrong

javascript - JavaScript 中的 PHP JSON 变量

JavaScript:获取光标在 contenteditable div 中的位置