【发布时间】:2021-10-08 11:16:00
【问题描述】:
我见过很多其他类似的问题,但没有一个对我有帮助,因此我不觉得我的问题是重复的。关于这个案例的所有问题都试图为字符串变量附加一个新的“含义”,而我已经有了这些变量,只是想使用一个字符串来访问那些预先存在的变量。
我在 JS 中几乎没有带有 ID 的 div 和几个名称与这些 ID 相同的字典。我想获取那些以字符串形式返回的 ID,并将它们用作访问这些字典的变量。
我尝试使用window[item.id] = idName,但我相信我不理解它,因为它不起作用。
我的代码:
<div id="id1" onclick="myfunc(this)"></div>
<div id="id2" onclick="myfunc(this)"></div>
<div id="id3" onclick="myfunc(this)"></div>
/* pre-existing variables I want to be able to use with IDs taken from function*/
id1={"name":"xxxx"}
id2={"name":"yyyy"}
id3={"name":"zzzz"}
function myfunc(item){
idName=item.id//returns string with id name
name=idName["name"]//doesn't work, as idName is a string and doesn't behave as a variable name;
}
【问题讨论】:
-
如果
id1、id2和id3在全局范围内,您可以从window获取它们。喜欢window[idName]
标签: javascript html string variables