2011-09-02 83 views
1

我有以下HTML結構:瞭解最後孩子

<div class="decorator"> 
    <div class="EC_MyICHP_Item"> 
     <div class="text"> 
      <h3><a target="_blank" title="" href="#"></a></h3> 
      text here text here text here text here text here text here 
     </div> 
    </div> 

    <div class="EC_MyICHP_Item"> 
     <div class="text"> 
      <h3><a target="_blank" title="" href="#"></a></h3> 
      text here text here text here text here text here text here 
     </div> 
    </div> 

    <div class="EC_MyICHP_Item"> 
     <div class="text"> 
      <h3><a target="_blank" title="" href="#"></a></h3> 
      text here text here text here text here text here text here 
     </div> 
    </div> 

    <div class="readmore"><a></a></div> 
</div> 

我想選擇上次EC_MyICHP_Item,利用最後的孩子,卻徒勞無功。 (CSS和jQuery)你能幫助我嗎?

謝謝。

+0

我在我的代碼中犯了一個錯誤:我剛剛添加了最後一個div。我相信這是干擾的,雖然它沒有相同的類名。 –

回答

4

您需要在選擇結束使用:last-child

div.EC_MyICHP_Item:last-child

http://reference.sitepoint.com/css/pseudoclass-lastchild

http://jsfiddle.net/jasongennaro/zrufd/

請注意:這不會在早期版本的IE瀏覽器的工作。

編輯

按照有關最後div註釋添加和干擾它。你是對的。它確實會導致:last-child嗆...至少在我測試過的Chrome中。

如果你的HTML結構保持不變,也就是永遠3 div.EC_MyICHP_Item,你可以這樣做

.EC_MyICHP_Item:nth-child(3)

更新了例:http://jsfiddle.net/jasongennaro/zrufd/1/

編輯#2

不幸的是的EC_MyICHP_Item DIV的電子數不同

在這種情況下,我會使用jQuery:

$('.EC_MyICHP_Item:last') 

進一步更新例如:http://jsfiddle.net/zrufd/2/

+0

我在代碼中犯了一個錯誤:我剛剛添加了最後一個div。我相信這是干擾的,雖然它沒有相同的類名。 –

+0

Ah-ha @George。看我的編輯。 –

+0

不幸的是,EC_MyICHP_Item div的數量各不相同:/ –

2

.EC_MyICHP_Item:last-child應該很好。

重要的是要認識到E:last-child的意思是「一個E元素,它是最後一個孩子」,而不是「E元素的最後一個孩子」。

0

如果DIV是最後一個子.EC_MyICHP_Item:last-child只會工作的母公司。由於您有div.readmore作爲父級的最後一個孩子,因此您的選擇器將無法工作。您需要改爲使用.EC_MyICHP_Item:last-of-type

編輯:在jQuery中這將翻譯爲.EC_MyICHP_Item:last

+0

最後一種類型的選擇器不工作(在小提琴中測試)我會嘗試jQuery的跨瀏覽器支持 –