【问题标题】:Direct descendant selector with greater than大于的直接后代选择器
【发布时间】:2012-10-15 23:29:16
【问题描述】:

我需要选择计数大于七的所有无序列表中的所有列表项。

这段代码:

$("ul.seven > li:gt(6)").hide()

过于贪婪,对页面上的第一个无序列表正常工作,但隐藏了后续无序列表的所有后续列表项。什么是正确的选择器?

【问题讨论】:

  • 如果您更喜欢“正确的选择器”而不是由选择器片段组成的回调代码块,请参阅我的回答。

标签: jquery css jquery-selectors


【解决方案1】:

试试这个

$("ul.seven").each(function() {
    $(this).find("> li:gt(6)").hide();
});

or(本质上是一样的)

$("ul.seven").each(function() {
    $(this).children("li:gt(6)").hide();
});

【讨论】:

    【解决方案2】:

    :gt() 整理ul.seven > li 的整个集合,并选择该组合集合中第六个li 之后的所有内容,而不管其父对象如何。这相当于选择所有这些li 元素,然后对结果集执行.slice()

    $("ul.seven > li").slice(7).hide();
    

    这与您的预期完全不同。

    你想要:nth-child(),而不是behaves more like what you expect of a CSS simple selector

    $("ul.seven > li:nth-child(n+8)").hide();
    

    :nth-child(n+8) 表示“基于 1-index 从第 8 个孩子开始”,大致相当于 :gt(6) 表示“基于 0-index 从第 7 个匹配开始”(令人困惑,我知道) .比较Selectors spec for :nth-child()jQuery API documentation for :gt()jQuery API documentation for .slice()

    【讨论】:

    • 感谢您对除了答案之外的确切问题的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    相关资源
    最近更新 更多