2015-04-03 73 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 } 
 

 
});