2014-10-06 63 views
-4

是什麼兩個語句之間的差:

$("span[id$='id']").text(var); 
    // And 
$("#id").text(var); 

HTML代碼:<span class="normal11" id="id"></span>

+0

第一個是屬性與選擇器結束,並且第二個是id選擇。這就是全部..:\ – 2014-10-06 10:04:21

+0

問題標題和問題身體不同...: - ? – 2014-10-06 10:05:02

+0

[id-selector](http://api.jquery.com/id-selector/)vs [Attribute Sends With Selector](http://api.jquery.com/attribute-ends-with-selector/) – 2014-10-06 10:06:36

回答

0

通過對文檔的JQuery的:

$("#id")使用JavaScript函數的document.getElementById(),這是非常有效的。 Link

所以,第二種方式應該更快,應該使用。

0

id選擇和屬性選擇器之間的一些不同的是

由於id選擇稱爲的document.getElementById(),它 只返回具有等於一個ID的第一個元素。

但是,如果使用屬性選擇器,它將返回所有具有與該屬性相同的id屬性的元素。

但是重複的id在HTML中實際上是無效的,並且不應該使用。

如果你真的想這樣做,請改用class。

例如

$("#id-selector").click(function(){ 
    $("#test").css("color", "red"); 
}); 
$("#attr-selector").click(function(){ 
    $("*[id=test]").css("color", "blue"); 
}); 

http://jsfiddle.net/toucyqas/1/

相關問題