我创建如果答案是通过点击切换问题的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的或类)。

有帮助吗?

解决方案

要做到这一点,最好的方法是使用每迭代直到你应该停止迭代的下一个元素。返回过程中的每个假停止迭代。使用过滤器,可以检查在迭代的元素的类型,并适当地作出反应。

$(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();
    });
  });
});

返回假从每个()结束该链

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

<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();
  });
});

下面是一种不使用。每个()的有趣的解决方案

$("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();

});

我被索引寻找下一个诗。不知道如何实践这个,但它是一个很好的锻炼。

我建议 jQuery的nextUntil();

$(document).ready(function(){
    $("p").hide();
    $("h3").click(function(){
        $("h3").nextUntil("h3").toggle();
    });
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top