删除除一个之外的所有类 [英] Remove all classes except one

查看:202
本文介绍了删除除一个之外的所有类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我知道有一些jQuery动作,我们可以添加很多类到特定的div:

 < ; div class =cleanstate>< / div> 

假设有一些点击和其他事情,div会得到很多类

 < div class =cleanstate bgred paddingleft allcaptions ...>< / div> 

那么,我如何删除除一个类之外的所有类?我想到的唯一的想法是这样:

  $('#container div.cleanstate')。removeClass addClass('cleanstate'); 

removeClass() ,div被拧紧了,但是添加后, addClass('cleanstate')它回到正常。另一个解决方案是将一个ID属性与基本的CSS属性,所以它们不会被删除,什么也提高性能,但我只是想知道另一个解决方案,除掉.cleanstate

$

解决方案

我想问这是因为在实际脚本中,div受到各种类别的更改。 div>

而不是在两个步骤中,你可以通过覆盖所有的类值用你想要的类来重新设置整个值与 attr

  jQuery('#container div.cleanstate')attr('class','cleanstate'); 

示例: http://jsfiddle.net/jtmKK/1/


Well, I know that with some jQuery actions, we can add a lot of classes to a particular div:

<div class="cleanstate"></div>

Let's say that with some clicks and other things, the div gets a lot of classes

<div class="cleanstate bgred paddingleft allcaptions ..."></div>

So, how I can remove all the classes except one? The only idea I have come up is with this:

$('#container div.cleanstate').removeClass().addClass('cleanstate');

While removeClass() kills all the classes, the div get screwed up, but adding just after that addClass('cleanstate') it goes back to normal. The other solution is to put an ID attribute with the base CSS properties so they don't get deleted, what also improves performance, but i just want to know another solution to get rid of all except ".cleanstate"

I'm asking this because, in the real script, the div suffers various changes of classes.

解决方案

Instead of doing it in 2 steps, you could just reset the entire value at once with attr by overwriting all of the class values with the class you want:

jQuery('#container div.cleanstate').attr('class', 'cleanstate');

Sample: http://jsfiddle.net/jtmKK/1/

这篇关于删除除一个之外的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆