【问题标题】:How to select and hide all but first 5 elements in a HTML file (DOM)如何在 HTML 文件 (DOM) 中选择和隐藏除前 5 个元素之外的所有元素
【发布时间】:2012-01-04 02:20:45
【问题描述】:

我正在尝试使用 coffeescript/jQuery 执行以下操作:

1) 检索显示在 html 中的所有“主题”(见下文)

2) 隐藏除列出的前 5 个主题之外的所有主题。

我尝试执行以下操作,但没有工作

//Retrieve the entire list of and hide all but the first 5 topics in the list
$(".topics .topic")[5..-1].hide()

谁能告诉我如何正确地从 HTML 文档中检索主题列表并随后隐藏除前 5 个主题之外的所有主题?

【问题讨论】:

    标签: jquery html dom hide coffeescript


    【解决方案1】:

    你的代码

    $(".topics .topic")[5..-1].hide()
    

    应该可以工作,因为它编译为 $(".topics .topic").slice(5).hide()jQuery's slice 完全符合您的要求。所以我猜你的代码在 DOM 处于正确状态之前正在运行。你试过了吗

    $(document).ready -> $(".topics .topic")[5..-1].hide()
    

    ?当你这样做时,你会得到什么

    alert $(".topics .topic").length
    

    在您的脚本中的同一点?

    如果问题不在于选择,那么问题一定出在hide(),它通过修改目标的内联 CSS 起作用。您可能会在代码的其他地方覆盖该 CSS。使用“检查元素”获取详细信息。

    【讨论】:

      【解决方案2】:

      查看jQuery gt() selector

      $(".topics .topic:gt(4)").hide();
      

      【讨论】:

        【解决方案3】:
        $(".topics .topic").slice(5).hide();
        

        http://api.jquery.com/slice/

        【讨论】:

        • 正确的想法,除了OP想要隐藏除前5个之外的所有内容,而不是隐藏前5个。
        • 这不能解决 OP 的问题,因为 CoffeeScript 代码 $(".topics .topic")[5..-1].hide() 就是这样编译的。 (Try it.)
        猜你喜欢
        • 1970-01-01
        • 2011-05-15
        • 1970-01-01
        • 2012-08-02
        • 2011-02-04
        • 2015-06-18
        • 2012-05-14
        相关资源
        最近更新 更多