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

时间:2009-07-03 15:54:29

标签: javascript jquery toggle next

我正在创建一个常见问题解答页面,通过点击问题来切换答案。问题是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>

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

$(document).ready(function(){
    $("p").hide();
    $("h3").click(function(){
        $(this).nextAll("p").toggle();
    });
});

我不能使用div或类。

4 个答案:

答案 0 :(得分:16)

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

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

答案 1 :(得分:8)

我会这样做:

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

从每个()返回false结束链。

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

<h3 class="question">Why is there no soup for me?</h3>
<div class="answer">
<p>...</p>
<p>...</p>
<p>...</p>
</div>

然后问题变得微不足道:

$(function() {
  $("div.answer").hide();
  $("h3.question").click(function() {
    $(this).next().toggle();
  });
});

答案 2 :(得分:1)

这是一个有趣的解决方案,不使用.each()

$("h3").click(function() {

    var idx = $("h3,p").index(this);
    var nextIdx = ($("h3,p").index($(this).nextAll("h3")));
    var nextPs = (nextIdx == -1) ? $("h3,p").length - idx : nextIdx - idx;
    $(this).nextAll("p:lt(" + (nextPs - 1) + ")").toggle();

});

我正在通过索引寻找下一个Ps。不确定这是多么实用,但这是一个很好的练习。

答案 3 :(得分:0)

我建议jQuery nextUntil();

$(document).ready(function(){
    $("p").hide();
    $("h3").click(function(){
        $("h3").nextUntil("h3").toggle();
    });
});