jQuery removeClass() 但不是某些类
如何从元素中删除除某些类之外的所有类。我假设我们不能将 not 与 removeClass()
一起使用。假设我有一个 并且我想删除除
aa dd
之外的所有类。我该怎么办呢。
How can I do remove all classes from an element except certain classes. I'm assuming we can't use not with removeClass()
. Let say I have a <div class="aa bb cc dd ee ff"></div>
and I want to remove all classes except aa dd
. How can I do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
为什么不将 class 属性替换为您想要的类,如下所示
Why don't you just replace the class attribute with the classes that you want like so
为了使其更简洁,您可以创建一个小扩展。
一样使用它
然后你可以像下面的例子
: http://jsfiddle.net/9xhND/ UPDATE
使用 Brad Christie 的逻辑,更新将现在只保留原来存在的类,而不添加新的类。 http://jsfiddle.net/9xhND/1/
To make it a little cleaner, you could create a little extension.
Then you could use it like
Heres an example: http://jsfiddle.net/9xhND/
UPDATE
Using Brad Christie's logic, the update will now only keep classes that were originally there and not add new classes. http://jsfiddle.net/9xhND/1/
.removeClass()
接受一个函数作为参数,该函数将返回要实际删除的类..所以
.removeClass()
accepts as a parameter a function that will return which classes to actually remove..so
您可以删除所有类并重新添加所需的类:
注意:在不指定特定类名的情况下调用
removeClass()
会删除所有类。You can remove all and add needed ones back:
Note: Calling
removeClass()
without specifying specific class name removes all classes.jQuery 实际上为removeClass 方法提供了一个回调参数,因此您可以使用一个简单的javascript 正则表达式来返回除您不想删除的类之外的所有类:
这样您就不会添加类“aa”和“bb” ' 如果它们还不存在。
您可以在此处查看其实际效果:http://jsfiddle.net/sr86u/3/
jQuery actually provides a callback parameter to the removeClass method, so you could use a simple javascript regular expression to return all the classes except the ones you don't want to remove:
This way you don't add classes 'aa' and 'bb' if they don't already exist.
You can see it in action here: http://jsfiddle.net/sr86u/3/
一种方法是用您想要保留的类覆盖所有类。因此,如果您的 div 的 id 为“myDiv”,那么您可以执行以下操作:
One way you can do it is to just overwrite all classes with the class(es) you want to keep. So, if your div has an id of "myDiv", then you could do:
如果您知道要保留哪些类,您可以重新添加它们(正如其他人已经展示的那样)。
我假设不知道这些类是否已经应用,所以我会更进一步:
If you know what classes you want to keep you can just re-add them (as others have already shown).
I'll assume though that it's not known whether those classes are already applied, so I'll take it a step further: