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

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

本文介绍了jQuery nextAll - 单击h元素切换所有p元素直到下一个h的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个常见问题解答页面,通过点击问题来切换答案。问题是 h3 ,答案是几个 p -elements。像这样:

I'm creating an FAQ page where the answer is toggled by clicking on the question. The question is h3 and the answer is several p-elements. Like this:

<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 -elements属于某个问题?我的JS切换页面上的所有 p - 元素:

How can I toggle all p-elements belonging to a certain question? My JS toggles all following p-elements on the page:

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

我不能使用 div 或类)。

推荐答案

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

The best way to do this is using each and iterating until you get to the next element that should stop the iteration. Returning false during an each stops the iteration. Using filter allows you to check the type of the element in the iteration and respond appropriately.

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

这篇关于jQuery nextAll - 单击h元素切换所有p元素直到下一个h的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 09:33