jquery活动类到基于当前url的菜单项

我有以下代码,如果菜单项url == current url,应该在菜单项中添加一个活动的css类:

$("#accordion a").each(function() { if (this.href.search(window.location.hostname) != -1) { $(this).addClass("active-sidebar-link"); } }); 

但是这会将类添加到所有菜单项中。 有小费吗?

试试这个:

 $("#accordion a").each(function() { if (this.href == window.location.href) { $(this).addClass("active-sidebar-link"); } }); 
 $('#accordion a[href="'+ window.location.hostname +'"]').addClass('active-sidebar-link'); 

如果你想用jQuery做到这一点,你可以:

 $("#accordion a").addClass(function(){ return this.href === window.location ? "active-sidebar-link" : "" ; }); 

但是,有一种更好的方式来设置当前页面链接的样式。 这通常涉及给body元素一个与您的链接对应的类名:

  Home Contact  

在这种情况下,您可以选择这样的活动链接样式:

 body.home a.home, body.contact a.contact { color: green; } 

此方法不需要JavaScript来设置初始样式,这总是好的。

使用过滤function:

 $("#accordion a") .filter(function(){ return location.href.match($(this).attr("href")) }) .addClass("active-sidebar-link"); 

仅返回已过滤的元素,在本例中,它们是与当前URL的链接,并将类active-sidebar-link到其中。