Find DOM element by ID when ID contains square brackets?(当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.
这篇关于当ID包含方括号时按ID查找DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当ID包含方括号时按ID查找DOM元素?


- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01