我已经硬编码了一个子导航,并希望通过简单地向这些链接添加一个“活动”类来突出显示当前页面的导航栏项目。但是下面的 HTML 标记与 javascript 结合将活动类添加到每个 li(.irp-menu-item) 而不仅仅是最近的 li。脚本必须只将类添加到最近的 li 而不是其他类,但不知何故我无法解决这个问题。
HTML标记:
<nav id="irp-subnav" class="css-sticky" role="navigation" aria-label="irp-subnav" lang="de-DE">
<div class="irp-wrapper">
<div class="irp-background"></div>
<div class="irp-content">
<span class="irp-title">
TITLE</span>
<div class="irp-menu">
<div class="irp-menu-tray">
<ul class="irp-menu-items">
<li class="irp-menu-item"><a href="/LINK-1/" class="irp-menu-link">LINK 1</a>
</li>
<li class="irp-menu-item"><a href="/LINK2/" class="irp-menu-link">LINK 2</a>
</li>
<li class="irp-menu-item"><a href="/LINK3/" class="irp-menu-link">LINK3</a>
</ul>
</div>
<div class="irp-actions irp-actions-right">
<div class="irp-action irp-action-menucta" aria-hidden="true">
<label for="irp-menustate" class="irp-menucta"> <span class="irp-menucta-chevron"></span>
</label>
</div>
</div>
</div>
</div>
</div>
</nav>
Javascript:
jQuery(document).ready(function($) {
$(function () {
var url = window.location.pathname;
var activePage = url.substring(url.lastIndexOf('/') + 1);
$('.irp-menu-item .irp-menu-link').each(function () {
var linkPage = this.href.substring(this.href.lastIndexOf('/') + 1);
if (activePage == linkPage) {
$(this).closest("li").addClass("active");
}
});
})
});