我的侧边栏上有一堆 <a href>
链接到同一页面
我有这个JS代码,但是之前的<a href>
链接不会变回tab-title
并保持活跃状态
我希望这样当用户单击链接时,<a href>
将从 class="tab-title"
更改至class="tab-title-active"
$(document).ready(function() {
$('a').click(function() {
$(this).removeClass('tab-title');
$(this).addClass('tab-title-active');
$(this).siblings().removeClass('tab-title-active');
$(this).siblings().addClass('tab-title');
console.log($(this).attr("class"));
});
});
a.tab-title{
font-size: 18px;
font-weight: 400;
list-style: none;
color: #444;
margin-top: 10px;
}
a.tab-title-active{
font-size: 18px;
font-weight: bold;
list-style: none;
color: #0091e4;
margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class="sidebar" style="position: fixed;">
<div class="tab">
<h5><a href="#tab-title-0" class="tab-title-active">Binary</a></h5>
</div>
<div class="tab">
<h5><a href="#tab-title-1" class="tab-title">About</a></h5>
</div>
<div class="tab">
<h5><a href="#tab-title-2" class="tab-title">Representation</a></h5>
</div>
</div>
<div class="content">
<h1 class="tab-title" id="tab-title-0">Binary</h1>
<p>
<!-- stuff written -->
</p>
<h1 class="tab-title" id="tab-title-1">About</h1>
<p>
<!-- stuff written -->
</p>
<h1 class="tab-title" id="tab-title-2">Representation</h1>
<p>
<!-- stuff written -->
</p>
</div>
最佳答案
$(document).ready(function() {
$('a').click(function() {
$('a').removeClass('tab-title-active');//this would remove active class from previous hyperlinks and the remaining code will apply the same
$(this).removeClass('tab-title');
$(this).addClass('tab-title-active');
$(this).siblings().removeClass('tab-title-active');
$(this).siblings().addClass('tab-title');
console.log($(this));
});
});
关于javascript - 单击时更改 javascript 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44363777/