这是我的菜单结构和Jquery。当前,当我在菜单中选择一个项目时,预期的行为是该项目本身具有一个活动类。如果在下拉列表中,则父级也应设置为活动状态。
我目前的问题是由于我的网址结构。我无法继续使用endWith,因为我的网址将以不同的结尾。但是,我也无法使用.contains,因为它的主页URL为“ /”
,它将把所有菜单项都设置为活动状态。我不确定目前如何进行
这是菜单结构
<div class="main-sidebar sidebar-style-2" tabindex="1" style="overflow: hidden; outline: none;">
<aside id="sidebar-wrapper">
<div class="sidebar-brand">
<a class="" href="/">Mercury</a>
</div>
<div class="sidebar-brand sidebar-brand-sm">
<a class="" href="/">M</a>
</div>
<ul class="sidebar-menu" id="navigation-menu">
<li><a class="nav-link" href="/"><i class="fas fa-home"></i><span>Home Page</span></a></li>
<li class="menu-header">Administrator Mode</li>
<li class="nav-item dropdown">
<a href="#" class="nav-link has-dropdown"><i class="fas fa-cog"></i><span>Configuration</span></a>
<ul class="dropdown-menu">
<li><a class="nav-link" href="/Configuration/AccountCodes">Account Codes</a></li>
<li><a class="nav-link" href="/Configuration/Branches">Branches</a></li>
<li><a class="nav-link" href="/Configuration/Users">Users</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a href="#" class="nav-link has-dropdown"><i class="fas fa-person-booth"></i><span>Directory</span></a>
<ul class="dropdown-menu" style="display: block;">
<li><a class="nav-link" href="/Directory/Users?Role=Administrator">Administrators</a></li>
<li><a class="nav-link" href="/Directory/Users?Role=Manager">Managers</a></li>
<li><a class="nav-link" href="/Directory/Users?Role=Agent">Agents</a></li>
</ul>
</li>
</ul>
</aside>
</div>
这是通过菜单中的URL时的控制台输出
/
#
/Configuration/AccountCodes
/Configuration/Branches
/Configuration/Users
#
/Directory/Users?Role=Administrator
/Directory/Users?Role=Manager
/Directory/Users?Role=Agent
到达/ Directory / Users网址时,仅输出/ Directory / Users。它没有显示?Role = Administrator部分。
这是我的Jquery代码
<script>
$(document).ready(function () {
var current = location.pathname;
console.log(current);
$("#navigation-menu a").each(function () {
var $this = $(this);
console.log($this.attr('href'));
if ($this.attr('href').endsWith(current)) {
console.log($this.parent());
$this.parent().addClass('active');
console.log("matched");
}
});
if ($(".dropdown-menu li").hasClass("active")) {
console.log("Yes");
var $this = $(this);
$(".dropdown-menu").parent(this).addClass('active');
console.log($(".dropdown-menu").parent(this));
}
});
</script>