简体   繁体   English

删除除 jquery 中的所有类之外的所有类的更干净的方法是什么,如果还没有该类,则也不添加该类

[英]What is the cleaner way to remove all classes except one in jquery, also without adding the class if there isn't the class already

Well, there is one popular way to clean all classes except one like嗯,有一种流行的方法可以清理所有类,除了像

 jQuery('#d-one label').attr('class', 'main');

But, the above code also adds main class even if there wasn't there at first.但是,即使一开始没有,上面的代码也添加了main类。

One workaround is to check if it has the class main or not and perform accordingly.一种解决方法是检查它是否具有main类并相应地执行。 But is there any way cleaner and shorter than this?但是有没有比这更清洁和更短的方法?

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="d-one"> <label for="" class="main one two three"></label> </div> <script> jQuery('#d-one label').attr('class', 'main'); console.log(jQuery('#d-one label').attr('class')); </script> <div id="d-two"> <label for="" class="one two three"></label> </div> <script> jQuery('#d-two label').attr('class', 'main'); console.log(jQuery('#d-two label').attr('class')); </script> <!-- This not just remove, but also add new class --> <div id="d-three"> <label for="" class="one two three"></label> </div> <script> if($( "#d-three label" ).hasClass( "main" )){ jQuery('#d-three label').attr('class', 'main'); }else{ jQuery('#d-three label').removeClass(); } console.log(jQuery('#d-three label').attr('class')); </script>

The following should work:以下应该工作:

jQuery('#d-one label').filter('.main').attr('class', 'main')
                      .end().not('.main').removeClass()

It first selects all <label> -elements under #d-one , then filters for class "main" and sets these to class="main" .它首先选择#d-one下的所有<label>元素,然后过滤类 "main" 并将它们设置为class="main" After that the filter is revoked ( .end() ) and all "non- .main " elements are cleared of all possible classes.之后过滤器被撤销( .end() )并且所有“非.main ”元素都被清除所有可能的类。

 $('#d-one label').filter('.main').attr('class', 'main') .end().not('.main').removeClass()
 .one {border: red 1px solid} .two {background-color: #ccc} .three {color: green} .main {font-weight:900}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="d-one"> <div id="d-four"> <label for="" class="main one two three">label: main stays and one two three removed!</label> </div> <div id="d-two"> <label for="" class="one two three">label: one two three removed!</label> </div> <div id="d-three"> <label for="" class="one two three">label: one two three removed!</label> </div> </div> </div> <div id="d-five"> <label for="" class="main one two three">label: main one two three - unchanged</label> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM