jQuery 在菜单上添加 .active 类

标签 jquery menu

我遇到了问题。

我想在相关页面打开时在项目菜单上添加“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/

如果是这个,我想添加一个类,即 link1 的“a”元素。

我尝试了很多解决方案,但没有任何效果。

最佳答案

Click here 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');
            }
        });

});

关于jQuery 在菜单上添加 .active 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4866284/

相关文章:

unity-game-engine - SceneManager.LoadScene(string) 无法识别场景名称

html - 分组的 CSS 菜单

javascript - 幻灯片图片消失

javascript - 如何使用 jQuery 按数据日期属性选择元素?

javascript - 如何在 sweet alert 2 中启用输入确认按钮

css - IE 7,8 中不显示水平菜单背景

jquery - 防止容器在点击时调整大小

javascript - 有人可以在幕后解释为什么这个 Jquery Hover 图像命令不起作用吗?

javascript - 如何防止 Javascript 菜单隐藏在 Flash 视频 (SWFObject) 下

html - 我如何获得像这张图片这样的 css html 菜单下拉菜单