jQuery 在菜单上添加类 .active [英] jQuery add class .active on menu
问题描述
我遇到了问题.
当相关页面打开时,我想在项目菜单上添加活动"类.
菜单很简单:
在 jQuery 中,我需要检查 url 是否为 www.xyz.com/other/link1/
如果是这个,我想在link1的'a'元素中添加一个类.
我尝试了很多解决方案,但没有任何效果.
点击这里查看 jsFiddle 的解决方案
你需要的是你需要获得如上所述的 window.location.pathname ,然后从中创建正则表达式并针对导航 href 对其进行测试.
$(function(){var url = window.location.pathname,urlRegExp = new RegExp(url.replace(//$/,'') + "$");//创建正则表达式以匹配当前 url 路径名并删除尾随斜杠(如果存在),因为如果尾随斜杠不存在,它可能与导航中的链接发生冲突//现在从导航中获取每个链接$('.menu a').each(function(){//并根据 url 路径名 regexp 测试其规范化的 hrefif(urlRegExp.test(this.href.replace(//$/,''))){$(this).addClass('active');}});});
I've got a problem.
I want to add the class "active" on item menu when the relative page is on.
the menu is very simple:
<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>
In jQuery I need to check if the url is www.xyz.com/other/link1/
if it's this one I would like to add a class one the 'a' element of link1.
I'm trying many solutions but nothing work.
Click here for a solution in jsFiddle
What you need is you need to get window.location.pathname as mentioned and then create regexp from it and test it against navigation 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');
}
});
});
这篇关于jQuery 在菜单上添加类 .active的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!