2014-10-06 120 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/

相关问题