jQuery Menu - Active State Based on URL

前端 未结 4 990
说谎
说谎 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: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');
    

提交回复
热议问题