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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:15:20  来源:igfitidea点击:

Selecting an ID with a colon in it with jQuery

javascriptjqueryidentifiercolon

提问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

回答by Facebook Staff are Complicit

From the jQuery ID Selector docs:

来自jQuery ID Selector 文档

If the id contains characters like periods or colons you have to escape those characters with backslashes.

如果 id 包含句点或冒号等字符,则必须使用反斜杠这些字符进行转义

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

Use the attribute equals selector.

使用属性等于选择器

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

回答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/

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