jQuery nextAll() — Click on h-element toggles all p-elements until next h
I found an example of jQuery code and I'm trying to adapt and implement it. I'm creating an FAQ page where the answer is toggled by clicking on the question. The question is h1 and the answer is several "p" elements.
Like this:
<h1>The First Question</h1>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>
<h1>Second Question</h1>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>
My JS code is:
$(document).ready(function(){
$(".accordion h1:first").addClass("active");
$(".accordion p:not(:first)").hide();
$(".accordion h1").click(function(){
$(this).next("p").slideToggle("slow")
.siblings("p:visible").slideUp("slow");
$(this).toggleClass("active");
$(this).siblings("h1").removeClass("active");
});
});
The problem is that this JS toggles just the first p element on the page. How can I toggle all p elements belonging to a certain question using NextAll()? Everything else is needed开发者_如何学编程 (sibling, etc), and I cannot use div's or classes.
Thanks!
Using the nextUntil()
(docs) method, you call select all the next elements until you reach a particular one.
In this case, we're using the not-selector
(docs) to select elements until we reach one that is not a <p>
element.
$(this).nextUntil(':not(p)').slideToggle(...
If you want to slideUp the other elements, you can use the not()
(docs) method to exclude the ones you just toggled.
var togg = $(this).nextUntil(':not(p)').slideToggle(...
togg.siblings('p:visible').not(togg).slideUp(...
精彩评论