jQuery在第二次点击时执行不同的操作?

时间:2015-04-03 02:39:29

标签: javascript 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>

3 个答案:

答案 0 :(得分: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;
});

答案 1 :(得分: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;
});

答案 2 :(得分:0)

这很好。

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

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

});