javascript - 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>
解决方案
很简单。只需删除所有类并仅设置为当前类。
$('.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');
});
推荐阅读
- angular - 带有 ContentChildren 的动态表单
- java - 如何从资源目录文件夹中的 .txt 文件中读取?
- wso2 - 读取 WSO2 EI 中的 LocalEntry 值
- spring-boot - 使用联接表存储库在@manytomany 中的 Spring 数据 jpa 规范和可分页
- ios - SwiftUI EKEventEditViewController 字段不可编辑
- swiftui - 带有 PresentationMode 的 SwiftUI NavigationView 在多级导航层次结构中创建错误
- angular - *ngIf 在 mat-table ng-container 中不起作用
- powerbi - Power Bi 嵌入式 A1。问题?
- r - 在 Quantstrat 中使用 add.indicator() 时出错
- javascript - Javascript 对象操作以创建具有变量 id 的对象列表