2012-01-23 20 views
1

我有以下代碼:jQuery的開放questionpart並關閉其他questionpart

<div class="faq"> 
<h1 class="question">Question</h1> 
<p class="answer">Answer</p> 
</div> 

<div class="faq"> 
<h1 class="question"> Question </h1> 
<p class="answer">Answer</p> 
</div> 

<div class="faq"> 
<h1 class="question"> Question </h1> 
<p class="answer">Answer</p> 
</div> 

,我喜歡點擊H1擴大了答案。 <p>標籤被設置爲顯示:無,但它是jquery,它正在擾亂我。具體要求:

  • 上H1的點擊,對應答案應該打開
  • 在另一個H1的點擊,其他問題的答案應該關閉,以及相應的答案應該打開
  • 上的H1而點擊答案是開放的,答案應該結束。

我已經試過如下:

jQuery(".faq > h1").click(function() { 
jQuery(this).siblings().hide(); 
jQuery(this).closest(".question").children("p").toggle("slow"); 

}); 

}); 

幾乎是卓有成效的,但在目前開放的問題的點擊,它關閉並重新打開它看起來檸車。

我該如何解決這個問題?

+0

你應該看看jQuery UI的手風琴。它會幫你找到工作。 http://docs.jquery.com/UI/Accordion –

回答

1
jQuery(".faq > h1").on('click', 
function() { 
    var $sib = jQuery(' + .answer', this); 
    jQuery('.answer:visible').not($sib).hide('fast'); 
    if($sib.is(':visible')) $sib.hide('slow'); else $sib.show('slow'); 
}); 

DEMO

+0

這兩個答案都與我的第一個解決方案一樣,但它仍然關閉,然後重新打開點擊答案。在這種情況下,如果它已經打開,我想關閉答案。 這應該用css屬性條件來完成嗎? –

+0

謝謝,但這並不能解決問題。它實際上什麼也不做,也許腳本錯誤? –

+0

@DaanTwice檢查出的演示,請。 – thecodeparadox

0

試試這個(隱藏所有的 「答案」 類的元素,然後只顯示當前選擇)

jQuery(".faq > h1").click(function() { 
    jQuery('.answer').hide(); 
    jQuery(this).next('.answer').show("slow"); 
});