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

查看:200
本文介绍了当ID包含方括号时,通过ID查找DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 某些东西[500] 

这是由我的Ruby on Rails应用程序构建的。我需要能够通过jQuery获取这个元素,以便我可以遍历DOM,以删除它的父代的父项,该父项具有我之前无法访问的变量ID。

$ b有没有人知道我可以怎么做?以下代码似乎不起作用:

  alert($(#something [+ id +]) .parent()的父()ATTR( ID))。。 

进一步检查以下内容:

  $(#something [+ id +])

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



任何帮助将不胜感激。

解决方案

您需要转义方括号,使其不被视为属性选择器。尝试这样:

  alert($(#something\\ [+ id +\\]) .parent()的父()ATTR( ID))。。 

请参阅选择器中的特殊字符,特别是第二段:


要使用任何元字符作为!#$%&'()* +,。/:;< =>?@ [\] ^``{|}〜)作为一个名称的字面部分,它必须用两个反斜杠进行转义: \\ 。例如,一个 id = foo.bar可以使用选择器 $(#foo\\bar)。W3C CSS规范包含< a href =https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier =nofollow noreferrer>关于有效CSS选择器的完整规则集,也很有用是Mathias Bynens针对标识符的CSS字符转义序列的博客条目。



I have a DOM element with an ID similar to:

something[500]

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+"]")

returns an object, but when I run ".html()" or ".text()" on it, the result is always null or just an empty string.

Any help would be greatly appreciated.

解决方案

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"));

See Special Characters In Selectors, specifically the second paragraph:

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天全站免登陆