当 ID 包含方括号时,按 ID 查找 DOM 元素?

我有一个 DOM 元素,其 ID 类似于:

something[500]

它是由我的 Ruby on Rails 应用程序构建的。我需要能够通过 jQuery 获取这个元素,这样我就可以遍历 DOM 来删除它父元素的父元素,它有一个变量 ID,我事先没有访问它的权限。

有人知道我该怎么做吗? 下面的代码似乎不起作用:

alert($("#something["+id+"]").parent().parent().attr("id"));

经进一步检查,如下:

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

返回一个对象,但是当我运行。Html ()或。“ text ()”时,结果总是 null 或者只是一个空字符串。

39849 次浏览

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.

Try this:

alert($("#something\\["+id+"\\]").parent()[0].parent()[0].attr("id"));

Square brackets have special meaning to jQuery selectors, the attribute filters specifically.

Just escape these and it will find your element fine

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

An id cannot include square brackets. It is forbidden by the spec.

Some browsers might error correct and cope, but you should fix you data instead of trying to deal with bad data.

You can escape them using \\ or you could do something like this...

$(document.getElementById("something[" + id + "]"))

You can also do

$('[id="something['+id+']"]')

"Any of the meta-characters

!"#$%&'()*+,./:;<=>?@[\]^`{|}~

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

" [source: jquery doc], and an element with id="foo[bar]" (even though not valid for W3C but recognised by JQuery), can use the selector

$("#foo\\[bar\\]")

(Just an asnwer like the many others, but all together :))