简体   繁体   English

jQuery last-child未定义问题

[英]jQuery last-child Undefined Issue

I have an issue getting the ID of my last-child with jQuery. 我有一个问题,用jQuery获取我的最后一个孩子的ID。

Here is my code with issue: http://jsfiddle.net/2ePeP/ 这是我的问题代码: http//jsfiddle.net/2ePeP/

My HTML code 我的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>

My JavaScript code 我的JavaScript代码

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

Any help will be greatly appreciated!!! 任何帮助将不胜感激!!!

Use :last or .last() 使用:last.last()

$('.category:last');

or 要么

$('.category').last()

DEMO DEMO

.last-child will only try to match the very last child of a parent element - see MDN :last-child , but the <button> is the last child in the parent <div> . .last-child只会尝试匹配父元素的最后一个子元素 - 请参阅MDN :last-child ,但<button>是父<div>的最后一个子元素。 There is no element with class="category" that is also a last child. 没有class="category"元素也是最后一个子元素。

CSS does provide a selector that will work, which matches CSS确实提供了一个匹配的选择器

the last occurrence of a specified element, even if it doesn't come dead last in the HTML. 最后一次出现的指定元素,即使它在HTML中不是最后一个。

(from CSS Tricks :last-child ) (来自CSS技巧:last-child

So the following will log the id of the last class="category" element. 所以下面将记录最后一个class="category"元素的id

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM