jQuery在菜单上添加类名“.active”

36

我有一个问题。

我想在相关页面时将项目菜单添加类"active"。

这个菜单非常简单:

<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>
在 jQuery 中,我需要检查 URL 是否为 www.xyz.com/other/link1/。
如果是这个 URL,我想要给 link1 的 'a' 元素添加一个类。
尝试了很多解决方案,但没有一个有效的。
16个回答

81

点击此处查看jsFiddle中的解决方案。

您需要做的是获取window.location.pathname,然后从中创建正则表达式,并将其与导航href进行测试。

$(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');
            }
        });

});

1
哦,是的,你是赢家!谢谢伙计! - Andrea Turri
2
尝试将urlRegExp行更改为urlRegExp = new RegExp(url == '/' ? window.location.origin + '/?$' : url.replace(/\/$/,'')); - Tom Tu
太棒了 - 通过评论中的urlRegExp,它运行良好 :) - Alexander Wigmore
请参考另一种更优雅的解决方案:http://stackoverflow.com/a/17706697/2332416 - RomanGor
所以我尝试了这个方法,它运行良好。但是当我在主页(www.foo.com/)时,所有的链接都会获得活动类... - moeses
显示剩余5条评论

22

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

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

因为我的链接是绝对路径,但如果你的链接是相对路径,则可以使用:

 window.location**.pathname**

如果您要将其与“pathname”第二种样式一起使用,请确保不包括星号,我相信OP在那里强调了它们,但它们并没有呈现出来。因此,您需要使用window.location.pathname。希望对您有所帮助。 - dashard
这是一个很好的解决方案,我稍微修改了一下,只是为了确保它影响菜单中的链接。因为正文内容中可能有相同的链接,如果父元素某种程度上是列表项,这可能会导致一些 CSS 问题。或者如果页脚中有快速菜单列表,也会受到影响。$('#primaryNav a[href="'+activeURL+'"]').parent('li').addClass('active'); 这可以确保它仅在我想要的位置添加活动类。 - Muhammad Russell

2
获取LI元素,循环遍历,检查HREF属性:
$('.menu').find('a').each(function() {
    if($(this).attr('href').indexOf('www.xyz.com/other/link1/')>0) {
          $(this).addClass('active');
    }
})

还没有任何东西...我需要查看URL的某些部分是否包含某些单词,如果是,则添加类... - Andrea Turri

2

看看这个 这个有效

Html

<div class="menu">

    <ul>
        <li><a href="~/link1/">LINK 1</a>
        <li><a href="www.xyz.com/other/link1">LINK 2</a>
        <li><a href="~/link3/">LINK 3</a>
    </ul>

</div>

Jquery

$(document).ready(function(){
    $(".menu ul li a").each(function(){
        if($(this).attr("href")=="www.xyz.com/other/link1")
            $(this).addClass("active");
    })
})

请详述Toro,我可以帮助你。 - Wazy

2

2

除了下面这种方法,我在菜单上给“a”元素添加类时没有找到其他可用的“addClass”方法:

$(function () {
        var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");  
        $('a').each(function () {
                            if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
                $(this).addClass('active');
            }
        });
    });

这让我花了四个小时才找到。

1
<script type="text/javascript">
    jQuery(document).ready(function($) {
    var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); 
    $("#navbar li a").each(function() {//alert('dsfgsdgfd');
    if(urlRegExp.test(this.href.replace(/\/$/,''))){
    $(this).addClass("active");}
});
}); 
</script>

1
这对我有用:D
    function setActive() {
      aObj = document.getElementById('menu').getElementsByTagName('a');
      for(i=0;i<aObj.length;i++) {
        if(document.location.href.indexOf(aObj[i].href)>=0) {
          var activeurl = window.location;
          $('a[href="'+activeurl+'"]').parent('li').addClass('active');
        }
      }
    }

    window.onload = setActive;

1
使用window.location.pathname并将其与您的链接进行比较。您可以像这样做:
$('a[href="~/' + currentSiteVar + '/"').addClass('active');

但首先您必须准备 currentSiteVar,以便将其放入选择器中。


1

我猜你正在尝试混合使用Asp代码和JS代码,但在某些时候它会出现错误或无法正确执行绑定调用。

也许你可以尝试使用委托代替。这将消除何时绑定点击事件的复杂性。

一个例子是:

$('body').delegate('.menu li','click',function(){
   var $li = $(this);

   var shouldAddClass = $li.find('a[href^="www.xyz.com/link1"]').length != 0;

   if(shouldAddClass){
       $li.addClass('active');
   }
});

看看这是否有帮助,它使用了 jQuery 的 属性开始选择器

Chi


使用ASP.NET可以实现,但不能使用ID。如果将URL的一部分与示例中的/link1/匹配,则会在相关菜单项上添加特定的类(可以使用不同的类进行调用)。 - Andrea Turri
嗨Toro,我已经更新了示例,请看看是否有帮助。它使用了jQuery的“属性以...开头”的选择器。 - Chi Chan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接