jQuery nextAll - 单击h元素切换所有p元素直到下一个h

Chr*_*oph 8 javascript jquery toggle next

我正在创建一个FAQ页面,通过单击问题来切换答案.问题是h3,答案是几个p元素.像这样:

<h3>The First Question</h3>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>

<h3>The Second Question</h3>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>
Run Code Online (Sandbox Code Playgroud)

如何切换p属于某个问题的所有元素?我的JS切换p页面上的所有后续元素:

$(document).ready(function(){
    $("p").hide();
    $("h3").click(function(){
        $(this).nextAll("p").toggle();
    });
});
Run Code Online (Sandbox Code Playgroud)

我不能使用div或类.

tva*_*son 16

执行此操作的最佳方法是使用each并迭代,直到到达应该停止迭代的下一个元素.在每次停止迭代期间返回false.使用过滤器可以检查迭代中元素的类型并进行适当的响应.

$(function() {
   $("p").hide();
   $("h3").click(function() {
       $(this).nextAll().each( function() {
           if ($(this).filter('h3').length) {
              return false;
           }
           $(this).filter('p').toggle();
       });
   });
});
Run Code Online (Sandbox Code Playgroud)


cle*_*tus 8

我会这样做:

$(function() {
  $("p").hide();
  $("h3").click(function() {
    $(this).nextAll().each(function() {
      if ($(this).is('h3')) {
        return false;
      }
      $(this).toggle();
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

从each()返回false结束链.

如果可能的话,我还建议更好地构建数据以处理这种情况.例如:

<h3 class="question">Why is there no soup for me?</h3>
<div class="answer">
<p>...</p>
<p>...</p>
<p>...</p>
</div>
Run Code Online (Sandbox Code Playgroud)

然后问题变得微不足道:

$(function() {
  $("div.answer").hide();
  $("h3.question").click(function() {
    $(this).next().toggle();
  });
});
Run Code Online (Sandbox Code Playgroud)