2013-10-14 30 views
2

我有一個問題,使用jQuery獲取我最後一個孩子的ID。jQuery最後一個孩子未定義問題

這裏是我的代碼有問題:http://jsfiddle.net/2ePeP/

我的HTML代碼

<div> 
    <p class="category" id="category_1">Appetizer</p> 
    <p class="category" id="category_2">Beaverages</p> 
    <p class="category" id="category_3">Dessert</p> 
    <button type="button" class="add-category">Add</button> 
</div> 

我的JavaScript代碼

$('.add-category').click(function() { 
    alert($('.category:last-child').attr('id')); 
}); 

任何幫助將不勝感激!

回答

4

使用:last.last()

$('.category:last'); 

$('.category').last() 

DEMO

+1

這是一個非常簡單的解決方案,解決了我的頭痛問題。非常感謝! – Lancelot

+0

請注意關於非(CSS)標準選擇器的[':last' ** Additional Notes **](http://api.jquery.com/last-selector/)部分。 – andyb

+0

非常感謝你的解決方案,我被困了幾個小時,'$('。category:last');'完全合作!!!!!出於某種原因,它不喜歡'last()' –

0

.last-child將只嘗試父元素的最後一個子匹配 - 見MDN :last-child,但<button>是父母<div>中的最後一個孩子。 class="category"也沒有元素,也是最後一個孩子。

CSS確實提供了一種選擇,將工作,它匹配

指定的元素最後出現的位置,即使它不來在HTML墊底。

(從CSS技巧:last-child

所以下面將記錄的最後一個class="category"元素的id

$('.add-category').click(function() { 
    console.log($('.category:last-of-type')[0].id); 
});