Javascript 使用 jQuery 选择带有冒号的 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7434215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting an ID with a colon in it with jQuery
提问by Geoff
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?
我正在为一个网站开发一个预先编写的模块,我需要定位一个带有 id 的元素test:two
。现在,该元素中有一个冒号,因此 jQuery 可能并且可以理解地将“二”视为伪类。有没有办法用 jQuery 定位这个元素?
Also, changing the ID is not possible. Believe me, if I could I would.
此外,无法更改 ID。相信我,如果可以的话,我会的。
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>
回答by Joseph Silber
Simply escape the colon with a \\
:
只需使用\\
:转义冒号:
$('#test\:two');
See the docs: How do I select an element by an ID that has characters used in CSS notation?.
回答by Facebook Staff are Complicit
From the jQuery ID Selector docs:
If the id contains characters like periods or colons you have to escape those characters with backslashes.
Because the backslash itself need to be escaped in the string, you'll need to do this:
因为反斜杠本身需要在字符串中转义,所以你需要这样做:
$("#test\:two")
$('#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>
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.
您现在还可以选择使用内置CSS.escape(...)
函数,该函数负责处理在选择器表达式中可能具有特殊含义的任何字符。
$("#" + CSS.escape("test:two"))
$('#test').css('background','red');
$(document.getElementById('test:two')).css('background','blue');
$("#" + CSS.escape("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>
回答by Rocket Hazmat
回答by JaredPar
Try using an attribute selector
尝试使用属性选择器
$(document).ready(function() {
$('div[id="test:two"]').each(function() {
alert($(this).text());
});
});
Fiddle: http://jsfiddle.net/zbX8K/2/