44

我正在为网站开发一个预先编写的模块,我需要使用 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>

4

4 回答 4

84

只需使用以下命令转义冒号\\

$('#test\\:two');

http://jsfiddle.net/zbX8K/3/


请参阅文档:如何通过具有 CSS 表示法中使用的字符的 ID 选择元素?.

于 2011-09-15T16:27:01.967 回答
18

jQuery ID 选择器文档

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

于 2011-09-15T16:27:23.590 回答
12

Use the attribute equals selector.

$('[id="test:two"]')
于 2011-09-15T16:27:46.500 回答
7

Try using an attribute selector

$(document).ready(function() {
    $('div[id="test:two"]').each(function() {
       alert($(this).text());
    }); 
});

Fiddle: http://jsfiddle.net/zbX8K/2/

于 2011-09-15T16:27:49.520 回答