Javascript jQuery - 从任何没有被点击的 <li> 中删除类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4901563/
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-23 14:40:21  来源:igfitidea点击:

jQuery - Remove class from any <li> that wasn't just clicked

javascriptjqueryhtml-listsremoveclasstoggleclass

提问by Joonas

Lets say I have list like this...

可以说我有这样的清单......

<ul>
  <li class="one">One</li>
  <li class="two">Two</li>
  <li class="three">Three</li>
</ul>

...and I want to be able to toggle class in the li's...

...而且我希望能够在 li 中切换类...

$( "li" ).click(function() {
    $( "li" ).toggleClass( "active" );
});

..also I want the li's except the one that was clicked to never show as '.active' while still maintaining the toggleClass ability in the '.active' li

..也我想要除了被点击的那个 li 永远不会显示为“.active”,同时仍然保持“.active” li 中的 toggleClass 能力

So I was thinking maybe I want to removeClass from any other li's except the one what was clicked. I don't know how I could do that though...

所以我在想也许我想从除了被点击的那个之外的任何其他 li 中删除类。我不知道我怎么能做到这一点...

Any ideas on how to achieve something like that? I'm sure its rather easy but I have no idea as I'm very new to jQuery

关于如何实现类似目标的任何想法?我确定它很容易,但我不知道,因为我对 jQuery 很陌生

Solved - If someone wants to see it.. there we go:http://jsfiddle.net/6jm2s/17/also this one...http://jsfiddle.net/6jm2s/18/

已解决 - 如果有人想看..我们去:http : //jsfiddle.net/6jm2s/17/还有这个... http://jsfiddle.net/6jm2s/18/

Both answers work perfectly.. @jondavidjohn & @hunter Thank you guys... too bad I can't put Checkmark on both answers... but I will let hunter have it as his code is shorter.. :)

两个答案都完美无缺..@jondavidjohn & @hunter 谢谢你们...太糟糕了,我不能在两个答案上都加上 Checkmark...但我会让 Hunter 拥有它,因为他的代码更短... :)

回答by hunter

Make it so that once something is active, one will always be active:

使它一旦某物处于活动状态,就会始终处于活动状态:

$("li:not(.active)").live("click", function() {
    $(this).addClass("active");
    $(this).siblings().removeClass("active");
});

focuses only on li's that aren't already active.

仅关注li尚未激活的 's。



To be able to deactivate:

为了能够停用:

$("li").click(function() {
    $(this).toggleClass("active");
    $(this).siblings().removeClass("active");
});

working example: http://jsfiddle.net/6jm2s/18/

工作示例:http: //jsfiddle.net/6jm2s/18/

回答by jondavidjohn

$( "li" ).click( function() {
    if( $(this).is('.active') ) {
        $(this).removeClass( "active" );
    }
    else {
        $( "li.active" ).removeClass( "active" );
        $(this).addClass( "active" );
    }
});