【问题标题】:jQuery last-child Undefined IssuejQuery last-child 未定义问题
【发布时间】:2013-10-14 17:16:00
【问题描述】:

我在使用 jQuery 获取我最后一个孩子的 ID 时遇到问题。

这是我有问题的代码: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'));
});

任何帮助将不胜感激!!!

【问题讨论】:

    标签: javascript jquery css-selectors


    【解决方案1】:

    使用:last.last()

    $('.category:last');
    

    $('.category').last()
    

    DEMO

    【讨论】:

    • 多么简单的解决方案,解决了我的头痛问题。非常感谢!
    • 请注意:last Additional Notes 非(CSS)标准选择器部分。
    • 非常感谢您的解决方案,我被难住了好几个小时,$('.category:last'); 完全成功了!!!!!!出于某种原因,它不喜欢last()
    【解决方案2】:

    .last-child 只会尝试匹配父元素的最后一个子元素 - 请参阅 MDN :last-child,但 &lt;button&gt; 是父元素 &lt;div&gt; 中的最后一个子元素。没有class="category" 的元素也是最后一个子元素。

    CSS 确实提供了一个可以匹配的选择器

    指定元素的最后一次出现,即使它没有在 HTML 中最后出现。

    (来自 CSS 技巧:last-child

    所以下面会记录最后一个class="category"元素的id

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 2013-03-03
      相关资源
      最近更新 更多