2012-01-07 5 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属性を削除するか、スクリプトが期待どおりに動作することを期待する場合は、少なくとも一意のIDを指定します。したがって、:lastセレクタを使用する場合は、たとえばidセレクタの代わりにクラスセレクタを使用できます(idセレクタでは:lastセレクタを使用することは意味がありません。これは、idセレクタが単一のDOM要素を返すため、

<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セレクター使用することができます:>あなたはDOMにこのIDを持つ唯一の要素を持つことができるよう=>)が理にかなって

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

を、ここですlive demo

+0

ありがとうございました! – Frank