我有一个 ID 类似于的 DOM 元素:
something[500]
它是由我的 Ruby on Rails 应用程序构建的。我需要能够通过 jQuery 获取这个元素,这样我就可以遍历 DOM 以删除它的父元素的父元素,它有一个我事先无法访问的变量 ID。
有人知道我该怎么做吗?以下代码似乎不起作用:
alert($("#something["+id+"]").parent().parent().attr("id"));
经过进一步检查,发现以下内容:
$("#something["+id+"]")
返回一个对象,但当我在其上运行“.html()”或“.text()”时,结果始终为空或只是一个空字符串。
最佳答案
您需要对方括号进行转义,这样它们才不会被算作属性选择器。试试这个:
alert($("#something\\["+id+"\\]").parent().parent().attr("id"));
See Special Characters In Selectors ,特别是第二段:
To use any of the meta-characters (such as
!"#$%&'()*+,./:;<=>?@[\]^``{|}~
) as a literal part of a name, it must be escaped with with two backslashes:\\
. For example, an element withid="foo.bar"
, can use the selector$("#foo\\.bar")
. The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.
关于javascript - ID包含方括号时按ID查找DOM元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1239095/