我尝试使用以下 javascript 来设置活动类
var url = window.location.pathname,
urlRegExp = new RegExp(url == '/' ? window.location.origin + '/?$' : url.replace(/\/$/, '')); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
// now grab every link from the navigation
$('.page-sidebar a').each(function () {
// and test its normalized href against the url pathname regexp
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});
问题是我需要在父<li>
元素上设置它,而不是<a>
我的 HTML 菜单示例
<div class="page-sidebar nav-collapse collapse">
<ul>
<li>
<div class="sidebar-toggler hidden-phone"></div>
</li>
<li class="start"> // HERE I NEED TO ADD CLASS ACTIVE
<a href="/default.aspx">
<i class="icon-home"></i>
<span class="title">Dashboard</span>
</a>
</li>
<ul>