如何使用jQuery选择具有非字母数字ID的元素? [英] How do I select an element with a non-alphanumeric id using jQuery?
问题描述
Axl Rose的Wiki页面包含一个ID为
Axl Rose's wiki page contains an element with the id:
1983.E2.80.931986:_Early_years
我正在使用$('#1983.E2.80.931986:_Early_years')
来获取此元素,但是失败了.
I'm using $('#1983.E2.80.931986:_Early_years')
to get this element but that fails.
如果我想通过ID选择此元素,正确的选择器是什么?
What's the correct selector to use if I want to select this element by id?
推荐答案
直接来自文档:>
Straight from from the docs:
如果您希望使用任何元字符(例如
!"#$%&'()*+,./:;<=>?@[\]^&a{|}~
)作为名称的文字部分,您必须 使用两个反斜杠对字符进行转义:\\.
例如,如果您 具有id="foo.bar"
的元素,则可以使用选择器$("#foo\\.bar")
.
If you wish to use any of the meta-characters (such as
!"#$%&'()*+,./:;<=>?@[\]^&a{|}~
) as a literal part of a name, you must escape the character with two backslashes:\\.
For example, if you have an element withid="foo.bar"
, you can use the selector$("#foo\\.bar")
.
推论:
jQuery.escapeSelector = function(str) {
return str.replace(/[!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~]/g, "\\$&");
}
// ...
$('#' + $.escapeSelector('1983.E2.80.931986:_Early_years'))
这篇关于如何使用jQuery选择具有非字母数字ID的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!