Using jQuery To Add Class Based On URL

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

提交回复
热议问题