删除除 jquery 中的一个类之外的所有类的更清洁的方法是什么,如果还没有类,也不添加类



好吧,有一种流行的方法可以清理除之外的所有类

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

但是,上面的代码也添加了main类,即使最初没有。

一种解决方法是检查它是否具有类main,并相应地执行。但是,还有比这更干净、更短的方法吗?

<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>

以下内容应该有效:

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

它首先选择#d-one下的所有<label>-元素;主";并将它们设置为CCD_ 5。之后撤销滤波器(.end()(;非CCD_ 7";元素被清除所有可能的类。

$('#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>

最新更新