简体   繁体   中英

Adding active class to current active link

I know this question is available on SO, but I have to ask this.
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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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