Using jQuery To Add Class Based On URL

后端 未结 4 775
無奈伤痛
無奈伤痛 2021-01-21 14:19

I\'m using jQuery and I\'m trying to add a class to a menu item based on URL. I tried this(found in other topics), but cannot get it to work properly. It adds the class to every

4条回答
  •  难免孤独
    2021-01-21 14:44

    I'd recommend giving your search links a class and doing something like:

    $(document).ready(function(){
       var current = window.location.pathname;
       $('.search-link').each(function(){
          var link = '/' + $(this).attr('href');
          if (current == link){
            $(this).parent().addClass('active');
          }
       }); 
    });
    

    This will compare the href of each link with the current pathname and add an active class if they match. The '/' in the link var is optional depending on whether or not it's already in the href.

    The $(this).parent().addClass('active') adds an active class to the parent 'li' element if the path matches which works well with bootstrap, but where you want the class and what it's called will depend on your css.

提交回复
热议问题