当ID包含方括号时按ID查找DOM元素?
我有一个 DOM 元素,其 ID 类似于:
I have a DOM element with an ID similar to:
something[500]
它是由我的 Ruby on Rails 应用程序构建的.我需要能够通过 jQuery 获取此元素,以便我可以遍历 DOM 以删除其父级的父级,该父级具有我无法事先访问的变量 ID.
which was built by my Ruby on Rails application. I need to be able to get this element via jQuery so that I can traverse my way up the DOM to delete the parent of it's parent, which has a variable ID that I don't have access to beforehand.
有人知道我该怎么做吗?以下代码似乎不起作用:
Does anyone know how I could go about this? The following code doesn't seem to be working:
alert($("#something["+id+"]").parent().parent().attr("id"));
经进一步检查,如下:
$("#something["+id+"]")
返回一个对象,但是当我在其上运行.html()"或.text()"时,结果始终为 null 或只是一个空字符串.
returns an object, but when I run ".html()" or ".text()" on it, the result is always null or just an empty string.
推荐答案
您需要对方括号进行转义,以免它们被计为属性选择器.试试这个:
You need to escape the square brackets so that they are not counted as attribute selectors. Try this:
alert($("#something\["+id+"\]").parent().parent().attr("id"));
查看选择器中的特殊字符,特别是第二段:
使用任何元字符(例如 !"#$%&'()*+,./:;<=>?@[]^``{|}~
) 作为名称的文字部分,必须使用两个反斜杠对其进行转义:\
.例如,带有 id="foo.bar"<的元素/code>,可以使用选择器
$("#foo\.bar")
.W3C CSS 规范包含 关于有效 CSS 选择器的完整规则集.同样有用的是 Mathias Bynens 在 标识符的 CSS 字符转义序列.
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.
相关文章