简体   繁体   English

向当前活动链接添加活动类

[英]Adding active class to current active link

I know this question is available on SO, but I have to ask this. 我知道这个问题可以在SO上找到,但是我不得不问这个。
I have made a plugin for my navigation with several functions and events. 我为导航创建了一个插件,其中包含一些功能和事件。
One method is to add an active class to the current link. 一种方法是将活动类添加到当前链接。
The method was working fine before but I have made some changes and now it is no longer working. 该方法以前运行良好,但我进行了一些更改,现在不再起作用。

My method is: 我的方法是:

$('.nav-menu li a').filter(function(){
    return this.href == location.href.replace(/#.*/, "");
}).addClass("active");

It's a very simple method but I need to write it again. 这是一个非常简单的方法,但我需要再次编写。
There are several functions and an event handler on that plugin. 该插件上有几个函数和一个事件处理程序。

There is a some selector working on a click event 在点击事件中有一些选择器

 $(document).on('click', '.nav-menu li a', function(e) {
    if ($(this).attr('href') !== '#') {
        var link = $(this).attr('href');
          $('#preloader').removeClass('fadeOut').addClass('fadeIn').fadeIn('slow');
            setTimeout(function() {
              window.location = link;
            }, 1500)
    } else if ($(this).attr('href') == '#') {
        e.preventDefault();
     }
 });

May be this.href is not giving you the absolute url. 可能是this.href没有为您提供绝对URL。 I am not sure though. 我不确定。 But it is better if you use indexOf which will work even if there is a relative url in the href. 但是,如果使用indexOf更好,即使href中有相对的url也可以使用。

$('.nav-menu li a').filter(function(){
    return location.href.replace(/#.*/, "").indexOf($(this).attr('href')) != -1;
}).addClass("active");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM