我们无法使用jQuery在JS代码中访问ID为"test:abc"的div元素.
<div id="test:abc">
$('#test:abc')
Run Code Online (Sandbox Code Playgroud)
没有结肠,它工作正常.我们无法控制ID生成,因为它是在Trinidad子表单中自动生成的,因为它将子表单ID附加:到其中的每个元素.
Tos*_*kan 84
简而言之
$(document.getElementById("test:abc")) 是你应该使用的.
说明:除了速度增益(见下文)外,它更容易处理.
示例:假设您有一个功能
function doStuff(id){
var jEle = $("#" + id); //is not safe, since id might be "foo:bar:baz" and thus fail.
//You would first have to look for ":" in the id string, then replace it
var jEle = $(document.getElementById(id)); //forget about the fact
//that the id string might contain ':', this always works
}
//just to give an idea that the ID might be coming from somewhere unkown
var retrievedId = $("foo").attr("data-target-id");
doStuff(retrievedId);
Run Code Online (Sandbox Code Playgroud)
速度/计时
你需要打开你的firebug控制台来获得结果.
我用firefox 10和jquery 1.7.2测试了它
基本上我做了一个选择10'000次div的id冒号 - 用不同的方法来实现它.然后我将结果与没有冒号的ID选择进行比较,结果非常令人惊讶.
在ms右选择器方法中剩余时间
299 $("#annoying\\:colon")
302 $("[id='annoying:colon']"
20 $(document.getElementById("annoying:colon"))
71 $("#nocolon")
294 $("[id='nocolon']")
Run Code Online (Sandbox Code Playgroud)
特别
71 $("#nocolon") and
299 $("#annoying\\:colon")
Run Code Online (Sandbox Code Playgroud)
有点意外
tva*_*son 29
显然,它在冒号上绊倒,因为jQuery试图将其解释为选择器.尝试使用id属性选择器.
$('[id="test:abc"]')
Run Code Online (Sandbox Code Playgroud)
我会使用document.getElementById,并将结果传递给jQuery()函数.
var e = document.getElementById('test:abc');
$(e) // use $(e) just like $('#test:abc')
Run Code Online (Sandbox Code Playgroud)