gpt4 book ai didi

jQuery 在菜单上添加 .active 类

转载 作者:行者123 更新时间:2023-12-03 21:29:58 25 4
gpt4 key购买 nike

我遇到了问题。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com