How to match URL with href in jQuery?

后端 未结 3 646
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-26 06:05

Using a list for navigation, I am looking for a clean way to apply the \'selected\' class to a list item if the page URL (minus anything after the path) matches the href of the

3条回答
  •  一个人的身影
    2021-01-26 06:31

    I guess if you keep your html like

  • dresses
  • but change the comparisson to:

    $('.leftNav li a').each(function(){
        if (this.href.indexOf(location.pathname) > -1) {
            $(this).parents('li').addClass('selected');
        }
    });
    

    you'll get what you need!

    The "if" above will check if the given path is contained in item's href property.

    So, if your URL is "http://www.yourhost.com/p/clothing/dresses/N-10635?param=value", it's path (/p/clothing/dresses/N-10635) should be found, and the output for the given example would be:

  • dresses
  • I hope this helped! =)

提交回复
热议问题