jQuery Menu - Active State Based on URL

前端 未结 4 975
说谎
说谎 2021-01-03 11:38

I am just trying to retrofit an active state into a static html menu. The menu has the following structure: -

ul id=\"MenuBar1\" cl
相关标签:
4条回答
  • 2021-01-03 12:21

    Checkout the fiddle here : http://jsfiddle.net/EVmsY/

    $(function(){
      var url = 'http://www.thesite.com/product1.htm'; // window.location;
      var page = url.substr(url.lastIndexOf('/') + 1);
    
      if (page) {
        $('#MenuBar1 li a[href="' + page + '"]').addClass('active');
        $('.active').parents().children('li a').addClass('active');
      }
    });
    
    0 讨论(0)
  • 2021-01-03 12:27

    You can get the current path with JavaScript using window.location.pathname. You can check with jQuery using something like:

    $("#navbar a[href=" + window.location.pathname + "]").addClass('active');
    

    This will add the active class to all anchors in #navbar that have the same href attribute as the current path. You may need to trim the leading slash.

    0 讨论(0)
  • use window.location.href to get the current current URL location of the browser... and addClass() to add a classname to the link... inmycase i am adding active

    try this

     <script>
     $(function(){
        var currenthref=window.location.href;
        $("#navbar a[href=" + currenthref + "]").addClass('active');  //adds active class to the current url.
    
    })
    </script>
    
    0 讨论(0)
  • 2021-01-03 12:40

    You could do something like this:

    var url = window.location.pathname;
    var filename = url.substring(url.lastIndexOf('/')+1);
    
    $('#MenuBar1 a').each(function() {
         if(filename == $(this).attr('href')) {
              $(this).addClass('active');
         }
    });
    

    If you need the class applied to the li do something like this:

    var url = window.location.pathname; var filename = url.substring(url.lastIndexOf('/')+1);

    $('#MenuBar1 a').each(function() {
         if(filename == $(this).attr('href')) {
              $(this).parent('li').addClass('active');
         }
    });
    

    The above responses will come out incorrect because they will give the full pathname so if your url is like this:

    http://www.thesite.com/about.htm 
    

    The "window.location.pathname" is going to return this:

    /about.htm
    

    So you would need to do something like this in order to leave the markup the way you have it and get the desired result or you could just prepend slashes to the front of the href.

    var url = window.location.pathname;
    var filename = url.substring(url.lastIndexOf('/')+1);
    
    $("#navbar a[href=" + filename + "]").addClass('active');
    
    0 讨论(0)
提交回复
热议问题