jQuery:最后一个选择器

时间:2012-01-07 15:38:49

标签: javascript jquery html

我正在使用这个jQuery代码

$('#share_module:last').css("background-color","red");

但它始终是第一个 #share_module

HTML结构有点像这样

<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>

但它只是第一个。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:11)

您不能拥有多个具有相同ID的DOM元素。这只是无效的HTML。首先修复标记并删除此id属性,或者至少提供一个唯一ID,如果您希望脚本按预期运行。因此,如果你想使用:last选择器,你可以使用类选择器而不是id选择器(使用:last选择器和id选择器是没有意义的,因为id选择器只返回一个单个DOM元素=&gt;因为您在DOM中只有一个具有此ID的元素=&gt;有意义):

<div class="share_module" >
    //then stuff inside
</div>
<div class="share_module" >
    //then stuff inside
</div>
<div class="share_module" >
    //then stuff inside
</div>
<div class="share_module" >
    //then stuff inside
</div>
<div class="share_module" >
    //then stuff inside
</div>

一旦您拥有有效的标记,就可以使用:last选择器:

$('.share_module:last').css("background-color","red");

这是一个live demo