javascript 使用 JQuery 添加“活动”类当前菜单项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12497289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:20:15  来源:igfitidea点击:

Adding 'active' class current menu item w/ JQuery

javascriptjqueryhtmlcss

提问by NallyRoll

There have been several SO solutions to this, but I haven't had any luck getting them to work. JQuery beginner trying to work through a solution to add an 'active' class to the active list item in a simple navigation menu:

对此有几个 SO 解决方案,但我没有让它们工作的运气。JQuery 初学者正在尝试通过一种解决方案将“活动”类添加到简单导航菜单中的活动列表项:

   <div id="main-menu">

      <ul>
         <li><a href="/site/about">About Us</a></li>
         <li><a href="/site/work">Our Work</a></li>
         <li><a href="/site/contact">Contact Us</a></li>    
      </ul>

    </div>

A previous SO post indicated that this worked, but I've had no success so far. I'm using pretty permalinks in wordpress, so the full path to any page is like:

以前的 SO 帖子表明这有效,但到目前为止我还没有成功。我在 wordpress 中使用了漂亮的永久链接,因此任何页面的完整路径如下:

http://www.foobar.com/site/about/

http://www.foobar.com/site/about/

This is my work so far:

这是我迄今为止的工作:

<script>
$(function(){
    var url = window.location.pathname,
        urlRegExp = new RegExp(url.replace(/\/$/,''));    
        $('#main-menu li').each(function(){
            if(urlRegExp.test(this.href)){
                $(this).addClass('active');
            }
        });
});?
</script>

I've tried several solutions, including changing how I write the href, etc. The part of the code I'm really foggy on is the urlRegExp part...Any help?

我已经尝试了几种解决方案,包括更改我编写 href 的方式等。我真正迷惑的代码部分是 urlRegExp 部分...有帮助吗?

回答by Fabrizio Calderan

try with

尝试

    $('#main-menu li a').each(function(){
        if(urlRegExp.test(this.href)){

        ...
    });

instead of

代替

    $('#main-menu li').each(function(){
        if(urlRegExp.test(this.href)){
        ...
    });

since hrefattribute you're looking on next line with this.hrefis applied on links, and not on list-items

因为href您在下一行查看的属性this.href应用于链接,而不是应用于列表项

then, if you need to apply the class activeon <li>element just use

然后,如果您需要active<li>元素上应用该类,只需使用

 $(this).parent().addClass('active'); 
 // or  $(this).closest('li').addClass('active');
 // or pure-JS : this.parentNode.className += 'active';

回答by Chris Dixon

this.href is wrong (should be $(this), plus you're checking on the list element, rather than li. Try this:

this.href 是错误的(应该是 $(this),而且你正在检查列表元素,而不是 li。试试这个:

$('#main-menu li > a').each(function(){
        if(urlRegExp.test($(this).attr('href'))){
            $(this).addClass('active');
        }
    });