我们无法使用jQuery在JS代码中访问ID为“ test:abc”的div元素。
<div id="test:abc">
$('#test:abc')
没有冒号就可以正常工作。我们无法控制ID的生成,因为它会以特立尼达子表单的形式自动生成,因为它会将子表单ID附加:到其中的每个元素。
我们无法使用jQuery在JS代码中访问ID为“ test:abc”的div元素。
<div id="test:abc">
$('#test:abc')
没有冒号就可以正常工作。我们无法控制ID的生成,因为它会以特立尼达子表单的形式自动生成,因为它会将子表单ID附加:到其中的每个元素。
Answers:
简而言之
$(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);
速度/时间
您需要打开Firebug控制台以获取结果。
我用Firefox 10和jQuery 1.7.2进行了测试
基本上,我在id中用冒号选择了div的10,000次-使用不同的方法来实现它。然后,我将结果与没有冒号的ID选择进行了比较,结果令人惊讶。
剩余时间(以毫秒为单位)右选择器方法
299 $("#annoying\\:colon")
302 $("[id='annoying:colon']"
20 $(document.getElementById("annoying:colon"))
71 $("#nocolon")
294 $("[id='nocolon']")
特别
71 $("#nocolon") and
299 $("#annoying\\:colon")
有点意外
$("#annyoing\\:colon"),29 $("[id='annyoing:colon']"),5 $(document.getElementById("annyoing:colon")),8 $("#nocolon"),31 $("[id='nocolon']")
$("#annoying\\:colon")还是$(document.getElementById("annoying:colon"))?
参考Toskan的答案,我更新了他的代码以使其更具可读性,然后输出到页面。
这是jbin链接:http ://jsbin.com/ujajuf/14/edit
。
此外,我还进行了多次迭代
Iterations:1000000
Results:
12794 $("#annyoing\\:colon")
12954 $("[id='annyoing:colon']"
754 $(document.getElementById("annyoing:colon"))
3294 $("#nocolon")
13516 $("[id='nocolon']")
更:
Iterations:10000000
Results:
137987 $("#annyoing\\:colon")
140807 $("[id='annyoing:colon']"
7760 $(document.getElementById("annyoing:colon"))
32345 $("#nocolon")
146962 $("[id='nocolon']")
尝试使用 $('#test\\:abc')