jQuery在子文件夹中的菜单上添加class .active

时间:2015-12-28 08:40:38

标签: jquery css addclass

我能够找到一个可靠的解决方案,如何根据页面的网址为菜单项添加“活动”类:

jQuery(function(){
    var page = window.location.pathname,
        find = new RegExp(page == '/' ? window.location.origin + '/?jQuery' : page.replace(/\/jQuery/,''));
    jQuery('nav a').each(function(){
        if(find.test(this.href.replace(/\/jQuery/,''))){
            jQuery(this).addClass('active');
        }
    });
});

然而,这不适用于子文件夹中的链接,我似乎无法找到使其工作的方法。我错过了什么?

2 个答案:

答案 0 :(得分:1)

这是我使用的,它适用于我的子文件夹中的菜单项

$(".menu-item").each(function() {
  if (this.href == window.location.href) {
    $(this).addClass("active");
  }
});

答案 1 :(得分:0)

jQuery(document).ready(function(jQuery){
        var url = window.location.href;
            jQuery('#nav a.level-top').filter(function() {
                return this.href == url;
        }).addClass('active');
        jQuery('#nav a.active').closest('li').addClass('active');
    });