2015-04-03 117 views
1

我在jQuery中有一個基本的手風琴。當用戶點擊該問題時,隱藏的答案顯示出來。目前,爲了讓答案消失,用戶必須點擊另一個問題。我希望保持不變,但如果再次單擊相同的問題,我還想讓答案消失。jQuery對第二次點擊執行不同的操作?

var allPanels = jQuery('.faq-single .faq-answer-section').hide(); 
 
jQuery('.faq-question').click(function() { 
 
    var nextAnswer = jQuery(this).next(); 
 
    jQuery(allPanels).not(nextAnswer).slideUp(); 
 
    nextAnswer.slideDown(); 
 
    jQuery(this).find('.faq-answer').show(); 
 
    return false; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="faq-single"> 
 
    <span class="faq-question"><span class="faq-question-icon"></span>Question?</span> 
 
    <span style="display:none;" class="faq-answer-section"><span class="faq-answer-icon"></span><span class="faq-answer">FAQ answer</span></span> 
 
</div> 
 

 
<div class="faq-single"> 
 
    <span class="faq-question"><span class="faq-question-icon"></span>Question?</span> 
 
    <span style="display:none;" class="faq-answer-section"><span class="faq-answer-icon"></span><span class="faq-answer">FAQ answer</span></span> 
 
</div> 
 

 
<div class="faq-single"> 
 
    <span class="faq-question"><span class="faq-question-icon"></span>Question?</span> 
 
    <span style="display:none;" class="faq-answer-section"><span class="faq-answer-icon"></span><span class="faq-answer">FAQ answer</span></span> 
 
</div>

+0

使用'.toggle()'代替'.show()'。 – Barmar 2015-04-03 02:43:01

+0

感謝您的建議,但沒有奏效。 – user715564 2015-04-03 02:44:27

+0

'jQuery(this).find('。faq-answer')'不匹配任何東西。 '.faq-answer'不是'.faq-question'的後代。 – Barmar 2015-04-03 02:57:28

回答

0

這個工作對我來說:

var allPanels = jQuery('.faq-single .faq-answer-section').hide(); 
jQuery('.faq-question').click(function() { 
    var nextAnswer = jQuery(this).next(); 
    if(jQuery(this).next().is(':visible')){ 
    jQuery(this).next().slideUp(); 
    }else{ 
    jQuery(allPanels).not(nextAnswer).slideUp(); 
    nextAnswer.slideDown(); 
    } 
    return false; 
}); 
+0

謝謝Seamus! – user715564 2015-04-03 03:04:29

1
var allPanels = jQuery('.faq-single .faq-answer-section').hide(); 
jQuery('.faq-question').click(function() { 
    var nextAnswer = jQuery(this).next(); 
    jQuery(allPanels).not(nextAnswer).slideUp(); 
    if (nextAnswer.is(":visible")) { nextAnswer.hide(); } else { nextAnswer.slideDown(); } 
    return false; 
}); 
+0

你試過這個嗎?我不認爲「答案」會包含任何內容。 – Barmar 2015-04-03 02:59:23

+0

@Barmar FAQ回答 2015-04-03 03:01:42

+1

但它不是'.faq-question'的後代,所以'$(this).find()'不會找到它。 – Barmar 2015-04-03 03:02:19

0

這是工作的罰款。

var allPanels = $('.faq-single .faq-answer-section').hide(); 
 
$('.faq-single').click(function() { 
 

 
\t if($(this).children('.faq-answer-section').is(':visible')){ 
 
\t \t 
 
\t \t $('.faq-single .faq-answer-section').hide(); 
 
\t }else{ 
 
\t \t $('.faq-single .faq-answer-section').hide(); 
 
\t \t $(this).children('.faq-answer-section').show("slide"); 
 
\t } 
 

 
});