jQuery在菜单上添加class .active

And*_*rri 34 jquery menu

我有一个问题.

我想在相关页面打开时在项目菜单上添加"活动"类.

菜单很简单:

<div class="menu">

<ul>
<li><a href="~/link1/">LINK 1</a>
<li><a href="~/link2/">LINK 2</a>
<li><a href="~/link3/">LINK 3</a>
</ul>

</div>
Run Code Online (Sandbox Code Playgroud)

在jQuery中,我需要检查网址是否为www.xyz.com/other/link1/

如果是这个我想添加第一类是link1的'a'元素.

我正在尝试很多解决方案,但没有任何效果.

Tom*_* Tu 73

点击这里查看jsFiddle中的解决方案

你需要的是你需要获得所提到的window.location.pathname,然后从中创建regexp并根据导航hrefs进行测试.

$(function(){

    var url = window.location.pathname, 
        urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
        // now grab every link from the navigation
        $('.menu a').each(function(){
            // and test its normalized href against the url pathname regexp
            if(urlRegExp.test(this.href.replace(/\/$/,''))){
                $(this).addClass('active');
            }
        });

});
Run Code Online (Sandbox Code Playgroud)

  • 尝试将urlRegExp行更改为`urlRegExp = new RegExp(url =='/'?window.location.origin +'/?$':url.replace(/\/ $ /,''));` (2认同)

小智 18

对我来说更简单的方法是:

var activeurl = window.location;
$('a[href="'+activeurl+'"]').parent('li').addClass('active');
Run Code Online (Sandbox Code Playgroud)

因为我的链接转到绝对网址,但如果您的链接是相对的,那么您可以使用:

 window.location**.pathname**
Run Code Online (Sandbox Code Playgroud)