繁体   English   中英

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

[英]jQuery nextAll — Click on h-element toggles all p-elements until next h

我正在创建一个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>

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

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

我不能使用div或类)。

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

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

我会这样做:

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

从each()返回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();
  });
});

这是一个有趣的解决方案,不使用.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。 不确定这是多么实用,但这是一个很好的练习。

我推荐jQuery nextUntil();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM