嗨,我正在尝试创建一个脚本,该脚本将在标签上添加活动类,并删除ul中的其他类。
它现在可以工作了,但是当我有多个导航时,它会切换所有导航。 那么我该如何让它只针对当前的 ul li 项目内部呢?
我的代码笔工作示例:https://codepen.io/andrelange91/pen/JZOawY
我的网页:
<div class="row">
<div class="col-12">
<div class="smallNav activeNav">
<ul role="tablist" class="nav nav-pills nav-pills-primary">
<li data-toggle="tab" role="tablist" aria-expanded="true" class="nav-item active">
<a data-toggle="tab" role="tablist" href="#undefined" class="nav-link active" aria-expanded="true">
Profile
</a>
</li>
<li data-toggle="tab" role="tablist" aria-expanded="true" class="nav-item active">
<a data-toggle="tab" role="tablist" href="#undefined" class="nav-link">
Settings
</a>
</li>
<li data-toggle="tab" role="tablist" aria-expanded="true" class="nav-item active">
<a data-toggle="tab" role="tablist" href="#undefined" class="nav-link">
Options
</a>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="largeNav activeNav">
<ul role="tablist" class="nav nav-pills nav-pills-primary flex-column">
<li data-toggle="tab" role="tablist" aria-expanded="true" class="nav-item active">
<a data-toggle="tab" role="tablist" href="#undefined" class="nav-link active" aria-expanded="true">
Profile
</a>
</li>
<li data-toggle="tab" role="tablist" aria-expanded="true" class="nav-item active">
<a data-toggle="tab" role="tablist" href="#undefined" class="nav-link">
Settings
</a>
</li>
<li data-toggle="tab" role="tablist" aria-expanded="true" class="nav-item active">
<a data-toggle="tab" role="tablist" href="#undefined" class="nav-link">
Options
</a>
</li>
</ul>
</div>
</div>
我正在处理的脚本:
$('.activeNav li a').click(function(e) {
e.preventDefault();
$('.activeNav ul').find('a').removeClass('active');
$(this).addClass('active');
});
在下面使用它
$('.activeNav li a').click(function(e) {
e.preventDefault();
$(this).closest('.activeNav').find('a').removeClass('active');//from the current element find the closest parent with the class activeNav and then find all links to remove the active class
$(this).addClass('active');
});