2012-01-07 56 views
2

我使用这个jQuery代码的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> 

但它只是第一个。任何人都可以帮忙吗?

回答

11

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

<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

+0

非常感谢! – Frank 2012-01-07 15:44:05