【问题标题】:jQuery - hide if previous element has a particular classjQuery - 如果前一个元素具有特定的类,则隐藏
【发布时间】:2011-01-24 23:10:20
【问题描述】:

我想隐藏所有 class="csc-content",其中前一个兄弟是 h4 class="faq"。

更新 错误:我认为这是错误的......之前的兄弟姐妹不是h4。但我希望你明白,如果“问题”有“常见问题”类,所有“答案”都应该被隐藏 /更新

这是html:

<div id="centerCol-1">
  <div id="c65" class="csc-default normal">
    <div class="csc-header csc-header-n1"><h4 class="faq">FAQ question1</h4></div>
    <div class="csc-content active"><p class="bodytext">Answer1</p></div>
  </div>
  <div id="c67" class="csc-default normal">
    <div class="csc-header csc-header-n2"><h4 class="faq">FAQ question2</h4></div>
    <div class="csc-content active"><p class="bodytext">Answer2</p></div>
  </div>
  <div id="c68" class="csc-default normal">
    <div class="csc-header csc-header-n3"><h4>not FAQ</h4></div>
    <div class="csc-content active"><p class="bodytext">Not an answer, just normal content</p></div>
  </div>
</div>

jQuery 应该是这样的:

// find all outer divs with class csc-default in the div centerCol-1
// test if they contain a header div with an h4 class faq
// go to next element and hide it. Error... this should be parents next element?
$("#centerCol-1 .csc-default").find("h4").is(".faq").next(".csc-content").hide();

BR。安德斯

【问题讨论】:

    标签: jquery parent next siblings


    【解决方案1】:

    您需要将adjacent 选择器与:has 选择器一起使用,如下所示:

    $('#centerCol-1 .csc-default .csc-header:has(.faq)+.csc-content').hide();
    

    Demo

    【讨论】:

    • 哇!多么令人难以置信的快速答案!很好的答案,但我问错了问题并在您回答时对其进行了编辑。
    【解决方案2】:

    等一下,您只想隐藏每个常见问题解答问题的答案 div?因此,如果h4 具有类.faq,则紧跟在父 div 之后的 div 会被隐藏:

    $("#centerCol-1 h4.faq").parent().next("div").hide();
    

    【讨论】:

      【解决方案3】:

      试试这个:

      $("#centerCol-1 .csc-content").filter(function() {
        return $(this).prev().find(".faq").length > 0;
      }).hide();
      

      【讨论】:

        猜你喜欢
        • 2015-10-10
        • 1970-01-01
        • 1970-01-01
        • 2013-05-08
        • 2021-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多