使用JQuery removeClass()删除除一个之外的所有类 [英] Using JQuery removeClass() to remove all classes but one
问题描述
好的,我有一个有趣的(好吧,对我很有意思,反正:) :)。
Okay, I've got an interesting one (well, interesting to me, anyway :) ).
我有一个情况我有一个div具有静态类值,但它也可以分配一个动态的辅助类。当用户进行选择时,需要删除任何现有的辅助类并添加新类。
I've got a situation where I have a div with a static class value, but it also can have a single, "secondary class" assigned that is dynamic. When the user makes a selection, any existing secondary class needs to be removed and the new class added.
忽略使用id值(项目标准使用该类。 ...无法更改),在添加新类之前,是否有一种优雅的方法可以简单地忽略第一个类并删除其他任何类?
Ignoring using an id value (standards for the project use the class . . . can't be changed), is there an elegant way to simply ignore the first class and remove whatever other class is there, before adding the new one?
示例开始HTML:
<div class="staticClass dynaClass1" />
示例JS:
function updateClass(newSecondaryClass) {
$(".staticClass") . . . **** remove any class besides "staticClass" ****
$(".staticClass").addClass(newSecondaryClass);
}
如果使用 updateClass调用该函数(dynaClass2 );
,生成的HTML应为:
If the function is called using updateClass("dynaClass2");
, the resulting HTML should be:
<div class="staticClass dynaClass2" />
我可以想办法使用 removeClass删除所有类();
并在添加新类时添加staticClass,或者使用 attr(class,staticClass+ newSecondaryClass);
,但我想知道是否有办法处理它而不必触及静态类?
I can think of ways of doing it involving just removing all classes using removeClass();
and adding "staticClass" back in when adding the new class, or using attr("class", "staticClass " + newSecondaryClass);
, but I'm wondering if there isn't a way to handle it without having to touch the static class at all?
最后,我想这是一个学术问题,比什么都重要。 。 。看起来它应该是可行的,但我不知道该怎么做。 :D
In the end, I guess this is an academic question, more than anything . . . just seems like it's something that should be doable, but I don't know how to do it. :D
推荐答案
您可以传递一个函数来删除类,它返回除静态类之外的所有类:
You can pass a function to remove class, which returns all but the static Classes:
$('.staticClass').removeClass(function(index, klass) {
return klass.replace(/(^|\s)+staticClass\s+/, '');
})
这是返回对象上的所有类,没有静态类,因此删除除静态类之外的所有类。
This is returning all the classes that are on the object, without the static one, and therefore removes all classes but the static one.
这篇关于使用JQuery removeClass()删除除一个之外的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!