如何使JavaScript Toggle打开所有div?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (97)

每一行我都使用相同的类,像以下所示:

$(document).ready(function() {
  $(".faq-article").click(function() {
    $(".faq-details").toggle();
  })
});
.faq-details {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="faq">
  <div class="faq-article">
    <div class="title-faq">Question 1</div>
    <div class="faq-details">answer</div>
  </div>
  <div class="faq-article">
    <div class="title-faq">Question 2</div>
    <div class="faq-details">answer 2</div>
  </div>
</div>
提问于
用户回答回答于

因为类有多个元素faq-article,在实施时toggle()在该类中,所有元素都会受到影响。若要获取当前单击的元素,必须针对click通过指定this,将$(".faq-details").toggle();改成$(this).find(".faq-details").toggle();$(".faq-details", this).toggle();

$(document).ready(function() {
  $(".faq-article").click(function() {
    $(this).find(".faq-details").toggle();
  })
});
.faq-details {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="faq">
  <div class="faq-article">
    <div class="title-faq">Question 1</div>
    <div class="faq-details">answer</div>
  </div>
  <div class="faq-article">
    <div class="title-faq">Question 2</div>
    <div class="faq-details">answer 2</div>
  </div>
</div>

用户回答回答于

需要用this作为搜索.faq-details元素:

$(document).ready(function() {
  $(".faq-article").click(function() {
    $(".faq-details", this).toggle();
  })
});
.faq-details {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="faq">
  <div class="faq-article">
    <div class="title-faq">Question 1</div>
    <div class="faq-details">answer</div>
  </div>
  <div class="faq-article">
    <div class="title-faq">Question 2</div>
    <div class="faq-details">answer 2</div>
  </div>
</div>

扫码关注云+社区

领取腾讯云代金券