我有这个菜单有ul和li以及孩子们。当用户单击并移动到链接页面时,我想设置一个活动类,以便突出显示该菜单项。由于页面更改,我将在本地存储中保存单击的菜单li id并使用该信息突出显示菜单项。 这是我到目前为止的代码 -
$(function() {
$('li.main').click(function(e) {
localStorage.setItem('thisLink', $(this).attr("data-id"));
e.stopPropagation();
});
$('.navbar-brand').click(function(e) {
localStorage.setItem('thisLink', 'dashboard');
e.stopPropagation();
});
window.onbeforeunload = function() {
// window relaod fix on logout
// return "Hello";
}
thisLink = localStorage.getItem('thisLink');
if (thisLink) {
$('#' + thisLink).addClass('active');
}
});
HTML菜单结构:
<nav class="sidebar-nav">
<ul>
<li data-id="dashboard" id="dashboard" class="main">
<a class="" href="<?php echo base_url(); ?>" aria-expanded="false">
<i class="icon-grid"></i>
<span class="">
Dashboard
</span>
</a>
</li>
<li data-id="users" id="users" class="main">
<a class="has-arrow" href="#" aria-expanded="false">
<i class="icon-user"></i>
<span class="">
Users
</span>
</a>
<ul aria-expanded="true" class="">
<li><a href="UserList">List User</a></li>
<li><a href="AddUser">Add User</a></li>
</ul>
</li>
<li data-id="user-role" id="user-role" class="main">
<a class="" href="Groups" aria-expanded="false">
<i class="icon-shuffle"></i>
<span class="">
Users Role
</span>
</a>
</li>
<?php } ?>
<li data-id="product" id="product" class="main">
<a class="has-arrow" href="#" aria-expanded="false">
<i class="icon-tag"></i>
<span class="">
Product
</span>
</a>
<ul aria-expanded="true" class="">
<li><a href="category">View Category</a></li>
<li><a href="subcategory">View Subcategory</a></li>
<li><a href="size">View Size</a></li>
<li><a href="color">View Color</a></li>
<li><a href="brand">View Brand</a></li>
<li><a href="prolist">List Product</a></li>
<li><a href="Product">Add Product</a></li>
</ul>
</li>
<li data-id="configuration" id="configuration" class="main">
<a class="" href="Settings" aria-expanded="false">
<i class="icon-settings" aria-hidden="true"></i>
<span class="">
Configuration
</span>
</a>
</li>
<?php } ?>
<li data-id="backup" id="backup" class="main">
<a class="" href="backupdb" aria-expanded="false">
<i class="icon-arrow-down-circle" aria-hidden="true"></i>
<span class="">
Backup
</span>
</a>
</li>
</ul>
</nav>
它是一个动态站点,问题是如果用户注销并再次登录,则会显示仪表板,但突出显示的项目仍然是单击最后一个菜单并保存在localstorage中。而且我必须为每个菜单项指定ID才能达到此目的,这使得该解决方案过于苛刻。 什么是JS / jQuery中更智能的解决方案?或PHP是唯一的解决方案?
答案 0 :(得分:0)
您是否可以获取该页面的URL,并从中快速查找?
类似的东西:
jQuery('nav.sidebar-nav li:has(a[href="'+ window.location.pathname +'"])').addClass('activeMenuItem');