当 ID 包含方括号时,按 ID 查找 DOM 元素? [英] Find DOM element by ID when ID contains square brackets?

查看:31
本文介绍了当 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"));

经过进一步检查,以下内容:

Upon further inspection, the following:

$("#something["+id+"]")

返回一个对象,但是当我在其上运行.html()"或.text()"时,结果始终为空或只是一个空字符串.

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 with id="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 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆