jQuery在菜单上添加class .active [英] jQuery add class .active on menu
本文介绍了jQuery在菜单上添加class .active的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有问题.
当相对页面打开时,我想在项目菜单上添加活动"类.
I want to add the class "active" on item menu when the relative page is on.
菜单非常简单:
<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中,我需要检查网址是否为www.xyz.com/other/link1/
In jQuery I need to check if the url is www.xyz.com/other/link1/
如果是这个,我想在link1的'a'元素中添加一个类.
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.
推荐答案
单击此处以获取jsFiddle中的解决方案
Click here for a solution in jsFiddle
您需要的是获取如上所述的window.location.pathname,然后从中创建regexp并针对导航hrefs进行测试.
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在菜单上添加class .active的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文