简体   繁体   中英

Add Active Navigation Class Based On Url for similar url

I am trying to add active class in navigation. I used this article. Add Active Navigation Class Based on URL

$(function(){
    var current = location.pathname;
    $('#nav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})

It worked well. But my issue is in this case.

/blog, /blogAds

If url is /blog, active class added to both nav items. Is there any solution for it?

Try this

if( new RegExp(location.pathname + "$").test( $this.attr('href') ) ) {
    $this.addClass('active');
}

Tested with:

new RegExp('\/blog$').test('/blogAds'); // returns false
new RegExp('\/blog$').test('/blog'); // returns true

Reference

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