jquery add / remove class from .parent()

♀尐吖头ヾ 提交于 2019-12-01 08:08:00

问题


i know this is incredibly easy but I have been writing and rewriting this function for an hour with no success:

On click I want to add "active" to the <li> of the clicked link and remove "active" from all the other <li>'s in the navbar.

HTML:

   <nav>
     <ul>
       <li><a href="http://0327ea8.netsolhost.com/#home" class="home">Home</a></li>
       <li><a href="http://0327ea8.netsolhost.com/blog/" class="blog">Blog</a></li>
       <li><a href="http://0327ea8.netsolhost.com/#catalog" class="catalog">Catalog</a></li>
       <li><a href="http://0327ea8.netsolhost.com/#authors" class="authors">Authors</a></li>
       <li><a href="http://0327ea8.netsolhost.com/#store" class="store">Store</a></li>
     </ul>
   </nav>

jQuery:

  // NAVBAR ADD ACTIVE
   $("nav ul li a").click(function(){
     $("nav ul li").removeClass('active');
     $(this).stop().animate();
     $(this).parent().addClass('active');
   });

This is adding the classes just fine but I can't get it to remove.

I've also tried separating it into to separate functions with no luck.

I have the .stop().animate() in there because I have a .animate() on the hover state of the links.

thanks!

edit:

this is the jQuery for the hover and the reason I have .stop().animate()

   $("nav ul li a, aside ul li.categories a, div.posts div.foot a").hover(function(){
     $(this).animate({'backgroundColor' : '#edf5e9'}, 200);
   },function() {
     $(this).animate({'backgroundColor' : '#ccd4c8'}, 600);
   });

I'm not sure why the .stop().animate() is wrong. If I don't have .animate() the active class won't stick, if I do, the active class does.

I still can't get the class to remove though :-/


回答1:


Try this:

$(this).parent().siblings().removeClass('active');



回答2:


Try something even simpler:

 $('li.active').removeClass('active');


来源:https://stackoverflow.com/questions/4718877/jquery-add-remove-class-from-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!