使用jQuery选择带冒号的ID

时间:2011-09-15 16:25:37

标签: javascript jquery identifier colon

我正在为网站编写预先编写的模块,我需要定位一个标识为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 个答案:

答案 0 :(得分:73)

只需使用\\

逃脱冒号
$('#test\\:two');

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


请参阅文档: How do I select an element by an ID that has characters used in CSS notation?

答案 1 :(得分:13)

来自the jQuery ID Selector docs

  

如果ID包含句点或冒号等字符,则必须escape those characters with backslashes

因为反斜杠本身需要在字符串中进行转义,所以你需要这样做:

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

您现在还可以选择使用内置的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>

答案 2 :(得分:11)

使用attribute equals selector

$('[id="test:two"]')

答案 3 :(得分:7)

尝试使用属性选择器

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

小提琴:http://jsfiddle.net/zbX8K/2/