【问题标题】:jQuery selector to get last child that doesnt have a classjQuery选择器获取最后一个没有类的孩子
【发布时间】:2011-06-27 20:33:29
【问题描述】:

我有一页嵌套的ULs 和LIs,我需要得到每个UL 的最后一个LI,所以我这样做:

$('li:last-child')

这很好用。

但我需要扩展它,以便它获取每个 UL 的最后一个子 LI,其中 LI 没有给定的类 (x)。例如:

<ul>
    <li class="x">1</li>
    <li>2</li>
    <li class="x">3</li>
    <li>4</li>
    <li>5</li>
    <li class="x">
        6
        <ul>
            <li class="x">7</li>
            <li>8</li>
            <li class="x">9</li>
            <li>10</li>
            <li>11</li>
            <li class="x">12</li>
            <li class="x">13</li>
        </ul>
    </li>
</ul>

我需要返回 LI 5 和 11(因为它们是父级 ul 中没有 .x 的最后一个孩子)

我怎样才能优雅地做到这一点?

【问题讨论】:

    标签: jquery-selectors


    【解决方案1】:

    过滤掉带有类的元素。

    $('li:not(.x):last-child')
    

    如果 li 元素中的类不同,也就是说,如果所有元素都不是 class="x" 则类似

    $('li[class=""]:last-child')
    

    【讨论】:

    • 这行不通,因为如果最后一个元素是x,last-child 不会选择最近的,前一个li 不是x
    【解决方案2】:

    使用map()(docs) 方法通过迭代&lt;ul&gt; 元素并返回最后一个不带x 类的&lt;li&gt; 子元素来创建一个jQuery 对象。

    示例: http://jsfiddle.net/e2Da7/2/

    var lastLisNoX = $('ul').map(function() {
        return $(this).children('li:not(.x)').get(-1);
    });
    

    编辑: 用问题中发布的 HTML 更新了我的 jsFiddle 示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 2012-11-04
      相关资源
      最近更新 更多