添加'活动'类当前菜单项w / JQuery [英] Adding 'active' class current menu item w/ JQuery
问题描述
这里有几个解决方案,但我没有运气让他们工作。 JQuery初学者试图通过一个解决方案来在一个简单的导航菜单中添加一个'活动'类到活动列表项:
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:
<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>
以前的SO帖子表明这个工作,但我迄今为止没有成功。我在Wordpress中使用漂亮的永久链接,所以任何页面的完整路径是:
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:
http://www.foobar.com/site/about/
这是我的工作:
<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>
我尝试过几种解决方案,包括改变我如何写href等。代码我真的很模糊是urlRegExp部分...任何帮助?
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?
推荐答案
试试
$('#main-menu li a').each(function(){
if(urlRegExp.test(this.href)){
...
});
而不是
$('#main-menu li').each(function(){
if(urlRegExp.test(this.href)){
...
});
因为 href
下一行 this.href
应用于链接,而不是列表项
since href
attribute you're looking on next line with this.href
is applied on links, and not on list-items
将活动
应用于< li>
元素只需使用
$(this).parent().addClass('active');
// or $(this).closest('li').addClass('active');
// or pure-JS : this.parentNode.className += 'active';
这篇关于添加'活动'类当前菜单项w / JQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!