Using jQuery To Add Class Based On URL

后端 未结 4 788
無奈伤痛
無奈伤痛 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.

提交回复
热议问题