使用 jQuery 选择带有冒号的 ID
我正在为一个网站开发一个预先编写的模块,并且我需要以 id test:two
为目标元素。现在,这个元素中有一个冒号,因此 jQuery 可以理解地将“two”视为伪类。有没有办法用 jQuery 来定位这个元素?
另外,无法更改 ID。相信我,如果可以的话我会的。
我整理了一个例子:
$('#test').css('background','red');
$(document.getElementById('test:two')).css('background','blue');
$('#test:two').css('background','green');
<script src="//code.jquery.com/jquery-1.6.3.js"></script>
<div id="test">test</div>
<div id="test:two">test two</div>
I'm working on a pre-written module for a site, and I need to target an element with the id test:two
. Now, this element has a colon in it, so jQuery is presumably and understandably seeing the 'two' as a pseudo class. Is there any way of targeting this element with jQuery?
Also, changing the ID is not possible. Believe me, if I could I would.
I've put together an example:
$('#test').css('background','red');
$(document.getElementById('test:two')).css('background','blue');
$('#test:two').css('background','green');
<script src="//code.jquery.com/jquery-1.6.3.js"></script>
<div id="test">test</div>
<div id="test:two">test two</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需使用
\\
转义冒号即可:http://jsfiddle.net/zbX8K/3/
请参阅文档:如何通过 ID 选择具有 CSS 表示法中使用的字符的元素?。
Simply escape the colon with a
\\
:http://jsfiddle.net/zbX8K/3/
See the docs: How do I select an element by an ID that has characters used in CSS notation?.
来自 jQuery ID 选择器文档:
由于反斜杠本身需要在字符串中转义,因此您需要执行以下操作:
您现在还可以选择使用内置的
CSS.escape(...)
函数,该函数负责处理选择器表达式内可能具有特殊含义的任何字符。From the jQuery ID Selector docs:
Because the backslash itself need to be escaped in the string, you'll need to do this:
You now also have the option of using the built-in
CSS.escape(...)
function, which takes care of any characters that could have special meaning inside of a selector expression.使用属性等于选择器。
Use the attribute equals selector.
尝试使用属性选择器
小提琴: http://jsfiddle.net/zbX8K/2/
Try using an attribute selector
Fiddle: http://jsfiddle.net/zbX8K/2/