使用JS通过常见问题解答扩展/折叠div

时间:2016-07-15 14:50:03

标签: javascript jquery html

我想在我的网站上添加一些问题/答案。首先,我只想让它显示问题,然后是用户点击问题的答案。到目前为止,这是有效的,但是我如何得到它,以便当点击另一个时当前问题关闭?也就是说,一次只能打开一个问题

HTML

<div class="FAQs">

<div class="question"><span>Question?</span></div>
    <div class="answer">
        <p>Answer</p>
    </div>

<div class="question"><span>Question?</span></div>
    <div class="answer">
        <p>Answer</p>
    </div>


<div class="question"><span>Question?</span></div>
    <div class="answer">
        <p>Answer</p>
    </div>

<div class="question"><span>Question?</span></div>
    <div class="answer">
        <p>Answer</p>
    </div>

<div class="question"><span>Question?</span></div>
    <div class="answer">
        <p>Answer</p>
    </div>  

</div>

JS

$(".question").click(function () {

    $question = $(this);
    $answer = $question.next();
    $answer.slideToggle(500, function () {
        $question.text(function () {
            return $answer.is(":visible") ? $.question : $.question;
        });
    });

});

2 个答案:

答案 0 :(得分:2)

在您展示点击后,隐藏所有其他.answer元素:

  

$(&#39;。答&#39)。效果基本show();

&#13;
&#13;
$(".question").click(function() {
  $('.answer').slideUp();
  $question = $(this);
  $answer = $question.next();
  $answer.slideToggle(500, function() {
    $question.text(function() {
      return $answer.is(":visible") ? $.question : $.question;
    });
  });

});
&#13;
.answer {
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="FAQs">
  <div class="question"><span>Question?</span>
  </div>
  <div class="answer">
    <p>Answer</p>
  </div>
  <div class="question"><span>Question?</span>
  </div>
  <div class="answer">
    <p>Answer</p>
  </div>
  <div class="question"><span>Question?</span>
  </div>
  <div class="answer">
    <p>Answer</p>
  </div>
  <div class="question"><span>Question?</span>
  </div>
  <div class="answer">
    <p>Answer</p>
  </div>
  <div class="question"><span>Question?</span>
  </div>
  <div class="answer">
    <p>Answer</p>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$(".question").click(function (e) {
    $question = $(this);
    $answer = $question.next();
    $(".answer").slideUp();
    $answer.stop().slideToggle(500);
});
.answer
{
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="faqs">

<div class="question"><span>Question?</span></div>
    <div class="answer">
        <p>Answer</p>
    </div>

<div class="question"><span>Question?</span></div>
    <div class="answer">
        <p>Answer</p>
    </div>


<div class="question"><span>Question?</span></div>
    <div class="answer">
        <p>Answer</p>
    </div>

<div class="question"><span>Question?</span></div>
    <div class="answer">
        <p>Answer</p>
    </div>

<div class="question"><span>Question?</span></div>
    <div class="answer">
        <p>Answer</p>
    </div>  

</div>