Javascript /jquery为什么不把字符串作为变量

javascript/jquery why does taken string not hold as a variable?

本文关键字:变量 字符串 jquery 为什么不 Javascript      更新时间:2023-09-26

我尝试从元素中获取"name"属性,并使用该字符串调用一个已经存在的变量。

就是HTML (li是函数的目标):::

<ul name="editor">
    <li><a href="#">Politics</a></li>
    <li><a href="#">Finance</a></li>
</ul>

获取名称并将其用于函数"getCursor":::这行不通,为什么

var messa = $(item).parent().attr("name"); //getting name which is "editor"
start_cursor = messa.getCursor()

只有当我"硬编码"变量时,它才能工作,像这样:

start_cursor = editor.getCursor()

"editor"是这样预定义的(Codemirror):

var editor = CodeMirror.fromTextArea(document.getElementById("code"), 
{mode: "javascript"});

我想通过从ul中获取字符串名来动态地创建它。

感谢您的宝贵时间和智慧

要从字符串切换到javascript中定义的内容,请尝试

objectTheVarIsDefinedIn[nameOfVariable]

在这种情况下,我不确定你使用的是哪个对象/作用域/函数,我猜一般作用域应该是

window[messa].getCursor();

或者也许你使用了一个函数,你仍然在同一层:

this[messa].getCursor();

仅仅因为某些东西有相同的名字而不命名并不意味着它们是相同的东西。按照你的逻辑,我可以把某个东西命名为document,它就是document。

var mydoc = "document";
mydoc.location; //won't work because mydoc is just a string, it isn't the document object.

messa在本例中是一个字符串。不能在字符串上调用getCursor()。

然而,editor在这个例子中现在是窗口对象的属性,所以你可以这样做:

window[messa].getCursor();