Using jQuery To Add Class Based On URL

后端 未结 4 739
無奈伤痛
無奈伤痛 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:28

    You need a break after each case or else it will just go on to the next one.

    switch (window.location.pathname) {
        case '/p/about.html':
           $('.nav-about').addClass('current');
           break;
        case '/search/blog':
           $('.nav-blog').addClass('current');
           break;
        case '/p/design.html':
           $('.nav-design').addClass('current');
           break;
        case '/p/photography.html':
           $('.nav-photography').addClass('current');
           break;
        case '/p/hosting.html':
           $('.nav-hosting').addClass('current');
           break;
    }
    

    Side point, this is repetitive:

      $(document).ready(function(){
        $(function() {
    

    Both of those mean the same thing, use one of them.

    0 讨论(0)
  • 2021-01-21 14:34

    I'll make a different suggestion. From the examples you have given, it would be very possible to extract the elements class from the URL itself:

    var url = window.location.pathname;
    var elementName = url.match(/\/(\w+)\.?\/?$/);
    $('.nav-' + elementName).addClass('current');
    

    The regular expression matches:

    1. \/ - a slash character (needs to be escaped).
    2. (\w+) - more than one word character. This is also being "captured" and returned.
    3. \.? - a literal dot character (needs to be escaped too). This is to match the begining of a file extension like.php or .html. The question mark makes it optional.
    4. \/? - a literal slash character (needs to be escaped too). This is to match a trailing slash for URL's like /members/. The question mark makes it optional.
    5. $ - matches the end of a string.

    The nav elements full class name is then made up from a concatenation of .nav- and what ever was matched and captured from the regular expression.

    It really depends on the formatting of your URL's but for your example URL's this would work just fine. This code really allows you to by the DRY mindset - Don't Repeat Yourself.

    0 讨论(0)
  • 2021-01-21 14:37

    If the element you're adding the current class to has a href value relative to the current page's URL this method will likely be easier for you.

    You could probably simplify this a bit..

    Let's say you're on the following page: http://domain.com/page.html

    var current_location = window.location.href.split('/'); // ['http:', '', '', 'domain.com', 'page.html']
    var page;
    
    page = current_location[current_location.length - 1]; // the length of the current_location array is 5, subtract one to get the value of the 4th index - which is page.html
    
    $('a[href*="' + page + '"]').addClass('current'); // find a link on the page that links to page.html (current page) and add a class of `current` to this URL
    

    Here's an example on jsbin: http://jsbin.com/uzoyis/1

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题