2011-02-14 90 views
0

我找到了一個jQuery代碼的例子,我試圖去適應和實現它。我正在創建一個常見問題解答頁面,通過點擊問題來解答問題。問題是H1,答案是幾個「P」元素。jQuery nextAll() - 點擊h元素切換所有p元素,直到下一個h

像這樣:

<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> 

我的JS代碼:

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

}); 

的問題是,這個JS切換頁面上只是第一個p元素。如何使用NextAll()切換屬於某個問題的所有p元素?其他一切都需要(兄弟姐妹等),我不能使用div或類。

謝謝!

+0

好嗎?它有用嗎? – user113716 2011-02-14 22:33:54

回答

2

使用nextUntil()(docs)方法,您可以調用選擇所有下一個元素,直到到達特定元素。

在這種情況下,我們使用的是not-selector(docs),直到我們達到一個是一個<p>元素選擇元素。

$(this).nextUntil(':not(p)').slideToggle(... 

如果要效果基本show其他元素,你可以使用not()(docs)方法來排除你剛纔切換的人。

var togg = $(this).nextUntil(':not(p)').slideToggle(... 

togg.siblings('p:visible').not(togg).slideUp(... 
+0

這剛剛幫了我很大的忙!謝謝你,先生。 – 2011-11-15 12:23:01