我有一个带有嵌套菜单的侧边栏。该菜单包含链接。我希望当前选择的菜单项具有CSS类active
。我该怎么做?
https://jsfiddle.net/1wjba46j/
我的js看起来像这样:
var loc = window.location.href;
$('.nav-side-menu ul li a').each(function () {
var status = loc.indexOf($(this).attr('href')) > -1;
// $(this).toggleClass('active', status);
if (status) {
$(this).closest('li').addClass('active');
}
});
答案 0 :(得分:0)
这是一个普通的js解决方案。
// put your mapping here
var mapping = {
"http://example.org/page1": "css.path.to.your.element",
"http://example.org/page2": "path.to.other.element",
}
$(function(){
$(mapping[window.location.href]).addClass('active');
});
它只不过是页面网址和导航元素(他们的CSS路径)之间的简单映射。
如果该(子)菜单中的项目处于活动状态,您可能还想扩展菜单。所以你想要添加这样的东西:
$(mapping[window.location.href]).parent("ul").prev("li").addClass("active").click()
在需要的地方添加错误检查。