从导航链接添加和删除活动类

我一直在寻找有关如何在链接中添加和删除类的教程,但遗憾的是没有任何成功。 所有早期的问题都给了我一些理解,但没有给我我想要完成的结果。

我试图通过在单击链接时添加和删除类来为我的导航设置活动状态。

以下是我对JavaScript的看法:

$(document).ready(function(){ //active state $(function() { $('li a').click(function(e) { e.preventDefault(); var $this = $(this); $this.closest('li').children('a').removeClass('active'); $this.parent().addClass('active'); }); }); }); 

这是我的导航:

  

你是从最近的li的子元素中删除’active’类,然后你将活动类添加到当前a的父li 。 本着将活动类保留在锚点上而不是列表项的精神,这对您有用:

  $('li a').click(function(e) { e.preventDefault(); $('a').removeClass('active'); $(this).addClass('active'); }); 

活动链接是活动链接。 在任何给定时间都不会有多个链接处于活动状态,因此没有理由去除active类。 只需从所有锚点中删除即可。

演示: http : //jsfiddle.net/rq9UB/

尝试:

 $(function() { $('li a').click(function(e) { e.preventDefault(); var $this = $(this); $this.closest('ul').find('.active').removeClass('active'); $this.parent().addClass('active'); }); }); 

你的选择器正在查看当前( $(this) )元素的父元素,然后在该元素的子元素中查找a 。 该元素中唯一的a是您刚刚单击的元素。

我的解决方案向上移动到最近的ul ,然后找到element that currently has the class of active` element that currently has the class of元素,然后删除该类。

您发布的方法是将active类名添加到li元素,并且您希望从元素中删除类名。 我的方法使用li ,但是可以通过简单地从最后一行中删除parent()来修改它以使用a

参考文献:

  • children()
  • closest()
  • find()

我想你想要:

 $this.parents("ul").find("a").removeClass('active'); 

试试这个:

 $(function() { $('.start').addClass('active'); $('#main-nav a').click(function() { $('#main-nav a').removeClass('active'); $(this).addClass('active'); }); }); 

只需将类.start添加到您希望拥有类.active first的nav元素。

然后在你的css中声明类.active,如:

 #main-nav a.active { /* YOUR STYLING */ }