将类添加到最后一个 <li>在一组&lt;ul&gt; [英] Add class to the last &lt;li&gt; in a group of &lt;ul&gt;

查看:22
本文介绍了将类添加到最后一个 <li>在一组&lt;ul&gt;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组动态创建的

    ,我需要将一个类添加到每个的最后一个
  • .

    I have a group of <ul>'s created dynamically and i need a class added to the last <li> of each one.

    我有:

    $('ul li:last').each(function(){
        $(this).addClass("last");
    });
    

    但这只是在最后一个

      中添加了一个class="last",而不是所有
        的.

        But this only adds a class="last" to the last <ul> not in all of the <ul>'s.

        我希望每个

          的最后一个
        • 被添加到类中,而不仅仅是最后一个
            代码>.

            I want the last <li> of each <ul> to get added the class, not just the last <ul>.

            推荐答案

            :last,一个 jQuery 选择器,从集合中弹出最后一个元素并返回它.

            :last, a propriety jQuery selector, pops off the last element from the set and returns it.

            :last-child,CSS 选择器, 选择每个祖先元素的最后一个子元素.

            :last-child, the CSS selector, selects the last child of each ancestor element.

            $('ul li:last-child').addClass('last');
            

            jsFiddle.

            作为旁注,您不需要在那里使用 each().addClass() 将遍历 jQuery 集中的每个项目.

            As a side note, you don't need to use each() there. The addClass() will be ran over each item in the jQuery set.

            这篇关于将类添加到最后一个 <li>在一组&lt;ul&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆