jquery active class to menu item based on current url

后端 未结 4 956
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 07:58

I have the following code that should add an active css class to the menu item if menu item url == current url:

$(\"#accordion a\").each(function() 
{   
            


        
相关标签:
4条回答
  • 2020-12-16 08:39
    $('#accordion a[href="'+ window.location.hostname +'"]').addClass('active-sidebar-link');
    
    0 讨论(0)
  • 2020-12-16 08:40

    If you want to do this with jQuery, you can:

    $("#accordion a").addClass(function(){
      return this.href === window.location 
        ? "active-sidebar-link" 
        : "" ;
    });
    

    However, there's a far better way to style current-page links. This generally involves given the body element a classname that corresponds to your links:

    <body class="home">
       <a class="home" href="foo.html">Home</a>
       <a class="contact" href="bar.html">Contact</a>
    </body>
    

    In this case, you would select the active link styles like this:

    body.home a.home,
    body.contact a.contact {
      color: green;
    }
    

    This method doesn't require JavaScript to set the initial styles, which is always good.

    0 讨论(0)
  • Use a filter function:

    $("#accordion a")
    .filter(function(){ 
        return location.href.match($(this).attr("href"))
    })
    .addClass("active-sidebar-link");
    

    Returns only filtered elements, which in this case would be the link with the current URL and adds the class active-sidebar-link to it.

    0 讨论(0)
  • 2020-12-16 08:54

    Try this:

    $("#accordion a").each(function() {   
        if (this.href == window.location.href) {
            $(this).addClass("active-sidebar-link");
        }
    });
    
    0 讨论(0)
提交回复
热议问题