jquery 从 .parent() 添加/删除类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4718877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:48:14  来源:igfitidea点击:

jquery add / remove class from .parent()

jqueryaddclassremoveclass

提问by Thomas

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.

单击时,我想将“active”添加到<li>单击的链接的 ,并从<li>导航栏中的所有其他's 中删除“active” 。

HTML:

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:

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.

我在那里有 .stop().animate() 因为我在链接的悬停状态有一个 .animate() 。

thanks!

谢谢!

edit:

编辑:

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

这是悬停的 jQuery 和我有 .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.

我不确定为什么 .stop().animate() 是错误的。如果我没有 .animate() 活动类就不会粘住,如果我这样做了,活动类会粘住。

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

我仍然无法删除课程:-/

回答by treeface

Try this:

尝试这个:

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

回答by meagar

Try something even simpler:

尝试更简单的事情:

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