与另一位家长一起打开另一只手风琴时关闭手风琴

I have the following accordion setup: https://jsfiddle.net/n4tmjaqd/1/

如何调整功能,以使选项卡2或3打开时选项卡1关闭(反之亦然)?选项卡1与选项卡2和3具有不同的父级,尽管具有相同的类。甚至可能在同一个类的不同父级中都具有这样的功能,还是我需要调整例如Tab 1的父类名称并从那里创建一个新函数?指导深表感谢。

$(function() {

  $('.accordion .accordion-title').on('click', toggleAccordion);

  function toggleAccordion(event) {
    var target = $(event.target).closest('.accordion-item');

    target.parent('.accordion').find('.accordion-item').not(target).removeClass('is-open');
    target.toggleClass('is-open');
  }

});
.accordion .accordion-item {
  border-bottom: 1px solid #000;
}

.accordion .accordion-title {
  position: relative;
  padding: 15px;
  cursor: pointer;
}

.accordion .accordion-content {
  display: none;
  padding: 0 15px 15px;
}

.accordion .accordion-item.is-open .accordion-content {
  display: block;
}

.accordion .arrow {
  position: absolute;
  display: inline-block;
  padding: 5px;
  top: 13px;
  right: 15px;
  background-color: inherit;
  border: solid #000;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
}

.accordion .accordion-item.is-open .arrow {
  top: 20px;
  transform: rotate(-135deg);
  -webkit-transform: rotate(-135deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="accordion">
  <div class="accordion-item">
    <div class="accordion-title">
      TITLE 1
      <span class="arrow"></span>
    </div>
    <div class="accordion-content">
      CONTENT 1
    </div>
  </div>
</div>

<div class="accordion">
  <div class="accordion-item">
    <div class="accordion-title">
      TITLE 2
      <span class="arrow"></span>
    </div>
    <div class="accordion-content">
      CONTENT 2
    </div>
  </div>
  <div class="accordion-item">
    <div class="accordion-title">
      TITLE 3
      <span class="arrow"></span>
    </div>
    <div class="accordion-content">
      CONTENT 3
    </div>
  </div>
</div>
评论
  • 娃哈哈
    娃哈哈 回复

    Just add at the beginning of the click event handler like this (here is a fiddle):

    $(function() {
    
      $('.accordion .accordion-title').on('click', toggleAccordion);
    
       $('.accordion-item').removeClass('is-open');
        var target = $(event.target).closest('.accordion-item');
    
        target.parent('.accordion').find('.accordion-item').not(target).removeClass('is-open');
        target.toggleClass('is-open');
      }
    
    });