ในระยะสั้น
$(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);
ความเร็ว / เวลา
ดูที่jsbinนี้ซึ่งทดสอบและเปรียบเทียบความเร็วของวิธีการเลือกของ ID กับโคลอน
คุณต้องเปิดคอนโซล 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']")
โดยเฉพาะอย่างยิ่ง
71 $("#nocolon") and
299 $("#annoying\\:colon")
แปลกใจนิดหน่อย