Active navigation with jQuery - can't apply a default class to anchor

前端 未结 4 1372
天命终不由人
天命终不由人 2021-01-06 14:23

I am currently trying to make a navigation-menu where an active-class is applied to the anchors whose href attributes that match the c

相关标签:
4条回答
  • 2021-01-06 14:35

    This should do want you want: mark the matching link, and failing that, mark your default one.

    function markActiveLink() {
    
        //Look through all the links in the sidebar
       $("div#sidebar a").filter(function() {
    
          //Take the current URL and split it into chunks at each slash
          var currentURL = window.location.toString().split("/");
    
          //return true if the bit after the last slash is the current page name
          return $(this).attr("href") == currentURL[currentURL.length-1];
    
        //when the filter function is done, you're left with the links that match.
        }).addClass("active");
    
       //Afterwards, look back through the links. If none of them were marked,
       //mark your default one.
       if($("div#sidebar a").hasClass("active") == false) {
          $("div#sidebar h2:nth-child(2) a").addClass("active");
        }
     }
    
    markActiveLink();
    

    Also, I found an official tutorial on this on the jQuery Docs site - scroll to the bottom to see the jQuery code. It's tighter than mine, although it's not tailored to your situation.

    0 讨论(0)
  • 2021-01-06 14:50

    I think you can simplify this a bit:

    function highlightSelected()
    {
      $("h2.subnav a").each(
        function()
        {
          if (location.pathname.indexOf(this.href) > -1)
          {
            $(this).addClass("selected");
          }
        }
      );
    }
    
    0 讨论(0)
  • 2021-01-06 14:57

    great read.. but, I have to make a suggestion.. even if the JS works perfectly, you really should keep all menu list items within an Unordered List (or Ordered List),.. as a best practice.. :)

    0 讨论(0)
  • 2021-01-06 15:00

    Give this code a shot, its something I put together for the company that I work for.

    // highlight tab function
    var path = location.pathname;
    var home = "/";
    $("a[href='" + [path || home] + "']").parents("li").each(function() {   
        $(this).addClass("selected");
    });
    
    0 讨论(0)
提交回复
热议问题