Well, I know that with some jQuery actions, we can add a lot of classes to a particular 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属性放在一起,这样它们就不会被删除,这也会提高性能,但是我只想知道另一个解决方案,可以除go ".lean state"之外的所有属性

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

推荐答案

不需要分两步执行,只需用attr一次性重置整个值,方法是用所需的类覆盖所有类值:

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

样本:http://jsfiddle.net/jtmKK/1/

Jquery相关问答推荐

如何使用 jQuery 获取所有 ID?

如何在 jQuery 中获取浏览器滚动位置?

为什么 jquery fadeIn() 不能与 .html() 一起使用?

调用 jquery ajax - .fail vs. :error

jQuery Select 一个具有某个类的div,它没有另一个类

Select select2后触发动作

如何获取文档的滚动位置?

jquery beforeunload 关闭(不离开)页面时?

通过 AJAX 和 jQuery 使用 HTML5 文件上传

为不同的 node 类型配置jstree右键上下文菜单

使用 Jquery 更改页面标题

Javascript 使用哈希值重新加载页面

如何获得元素的正确偏移量? - jQuery

如何使用 javascript (jquery) 将整数值添加到返回字符串的值中?

jQuery $(".class").click(); - 多个元素,点击事件一次

Backbone.js - 事件,知道点击了什么

在jQuery中获取CSS规则的百分比值

$.getJSON 在 IE8 中返回缓存数据

如何使用新的 JSON 数据手动更新数据表

为什么我应该创建异步 WebAPI 操作而不是同步操作?