首页 > 解决方案 > jQuery .toggleClass 没有按预期工作

问题描述

我创建了一个迷你标签过滤器,但它不能正常工作。它仅在您一次单击和取消单击一个选项卡时才有效。现在,如果您单击一个选项卡,然后单击另一个选项卡,则先前单击的选项卡中的内容仍会显示先前单击的选项卡,当它不是假设时,它也会使类保持“当前”。我尝试用带注释的 JS 代码来解决这个问题,但这使得整个事情变得难以捉摸。谢谢!

$(document).ready(function () {

    $('.tab').click(function () {
        var tabID = $(this).data('tabid');

        // $('.iconsContainer').children().removeClass('current');
        $(this).toggleClass('current');

        // $('.iconContainerMore').removeClass('hideMoreText');
        $('.iconContainerMore', this).toggleClass('hideMoreText');

        // $('.tripctychContent-container').children().removeClass('showText');
        $('.tripctychContent-container').find("[data-blockid=" + tabID + "]").toggleClass('showTopicContent');
    });

});
.hideMoreText{
  display: none;
}

.hideTopicContent{
	display: none;
}

.showTopicContent{
    display: block;
}

.tab{
  cursor: pointer;
}
.iconsContainer{
    display: flex;
    justify-content: space-between;
}
.tab p:first-of-type{
  padding: 30px;
  background: blue;
  color: white;
}
.current p:first-of-type{
  background: black !important;
}
.tripctychContent-container p{
  background: red;
  color: white;
}
p{
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="iconsContainer">
  <a class="tab" data-tabid="topic1">
    <div>
      <p>Topic 1 title</p>
      <p class="iconContainerMore">More</p>
    </div>
  </a>
  <a class="tab" data-tabid="topic2">
    <div>
      <p>Topic 2 title</p>
      <p class="iconContainerMore">More</p>
    </div>
  </a>
  <a class="tab" data-tabid="topic3">
    <div>
      <p>Topic 3 title</p>
      <p class="iconContainerMore">More</p>
    </div>
  </a>
</div>

<div class="tripctychContent-container">
  <div class="field--name-field-topic-1-content hideTopicContent" data-blockid="topic1">
    <p>Topic 1 body</p>
  </div>
  <div class="field--name-field-topic-2-content hideTopicContent" data-blockid="topic2">
    <p>Topic 2 body</p>
  </div>
  <div class="field--name-field-topic-3-content hideTopicContent" data-blockid="topic3">
    <p>Topic 3 body</p>
  </div>
</div>

标签: javascriptjquery

解决方案


很简单。只需删除所有类并仅设置为当前类。

$('.tab').click(function () {
  var tabID = $(this).data('tabid');

  // remove all already set classes
  $('.iconContainerMore').removeClass('hideMoreText');
  $('.tripctychContent-container').find("[data-blockid]").removeClass('showTopicContent');

  // show current
  $('.iconContainerMore', this).addClass('hideMoreText');
  $('.tripctychContent-container').find("[data-blockid=" + tabID + "]").addClass('showTopicContent');
});

推荐阅读