我有一个侧边栏菜单,我用它来导航整个网站,我希望能够动态地将事件类添加到适当的菜单项。我试过使用下面的代码,但它似乎没有做任何事情。
var page = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
$('ul li a[href="'+ page +'"]').parent().addClass('active');
$('ul li a').filter(function() {
return this.href == page;
}).parent().addClass('active');
我的选择器语法可能有误,所以下面我包含了一个侧边栏的片段。
<div id="sidebar" class="nav-collapse ">
<ul class="sidebar-menu" id="nav-accordion">
<li>
<a href="dash.php">
<i class="fa fa-dashboard"></i>
<span>Home</span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-cogs"></i>
<span>Tools</span>
</a>
<ul class="sub">
<li><a href="index.php">Uptime</a></li>
</ul>
</li>
</ul>
</div>
最佳答案
我建议最简单的方法是过滤 <a>
的集合看哪个元素href
属性等于当前页面,然后将“事件”类名添加到最近的祖先 <li>
元素:
// caching the URL of the page:
var pageURL = document.location.href;
// selecting all <a> elements within the element with the
// id of 'nav-accordion'; then using the filter() method
// to filter the collection returned by the selector:
$('#nav-accordion a').filter(function (index, anchorEl) {
// only those elements for which this assessment returns
// Boolean true will be retained.
// here we test that the 'href' property (not the attribute),
// which is an absolute URL, is equal the current page's URL:
return anchorEl.href === pageURL;
// for those elements remaining in the collection we navigate to
// each retained element's closest ancestor '<li>' element and
// and then add the 'active' class-name to that <li>:
}).closest('li').addClass('active');
引用资料:
- JavaScript:
- >
document.location
. - >
URLUtils.href
.
- >
- jQuery:
- >
addClass()
. - >
closest()
. - >
filter()
.
- >
关于javascript - jQuery - 将事件类添加到菜单中的子菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32239130/