开发者

how to find all a hrefs that include current url with jQuery

开发者 https://www.devze.com 2023-03-22 18:23 出处:网络
I want to find all the href containing current url even if the whole href is longer. E.g. Current url: www.example.com/portfolio/

I want to find all the href containing current url even if the whole href is longer. E.g.

Current url: www.example.com/portfolio/

a href url: www.example.com/portfolio/#28

What I want to do is to add class to all <a>'s containing current url path (even if they are longer). I used something like this:

<script type="text/javascript">
var nav = $(location).attr('href');
if (nav) { 
jQu开发者_如何学编程ery('a[href$="' + nav + '"]').parent().addClass('current');
}
</script>   

But the code add the class only to 's containg the exact same path like current url.


Use the starts with selector:

<script type="text/javascript">
var nav = $(location).attr('href');
if (nav) { 
jQuery('a[href^="' + nav + '"]').parent().addClass('current');
}
</script> 
0

精彩评论

暂无评论...
验证码 换一张
取 消