jQuery removeClass()但不是某些类

Pin*_*kie 10 javascript jquery removeclass

除了某些类之外,如何从元素中删除所有类.我假设我们不能不使用removeClass().假设我有一个<div class="aa bb cc dd ee ff"></div>,我想删除所有类,除了aa dd.我怎样才能做到这一点.

Lau*_*rke 17

为什么不直接用你想要的类替换class属性

$('#yourElement').attr('class',"aa dd");
Run Code Online (Sandbox Code Playgroud)


Tim*_*nks 9

为了使它更清洁,你可以创建一个小扩展.

jQuery.fn.removeClassExcept = function (val) {
    return this.each(function () {
        $(this).removeClass().addClass(val);
    });
};
Run Code Online (Sandbox Code Playgroud)

然后你可以像使用它一样

$("selector").removeClassExcept("aa dd");
Run Code Online (Sandbox Code Playgroud)

下面是一个例子:http://jsfiddle.net/9xhND/

UPDATE

使用Brad Christie的逻辑,更新现在只保留原来的类而不添加新类. http://jsfiddle.net/9xhND/1/

jQuery.fn.removeClassExcept = function (val) {
    return this.each(function (index, el) {
        var keep = val.split(" "),  // list we'd like to keep
        reAdd = [],          // ones that should be re-added if found
        $el = $(el);       // element we're working on
        // look for which we re-add (based on them already existing)
        for (var c = 0; c < keep.length; c++){
          if ($el.hasClass(keep[c])) reAdd.push(keep[c]);
        }

        // drop all, and only add those confirmed as existing
        $el
          .removeClass()               // remove existing classes
          .addClass(reAdd.join(' '));  // re-add the confirmed ones
    });
};
Run Code Online (Sandbox Code Playgroud)


Gab*_*oli 7

.removeClass() 接受一个函数,它将返回实际删除的类.

所以

$('div').removeClass(function(i, class){
    // variable class hold the current value of the class attribute
    var list = class.split(' '); // we create an array with the classes
    return  list.filter(function(val){ // here we remove the classes we want to keep
        return (val != 'aa' && val != 'dd');
    }).join(' '); // and return that list as a string which indicates the classes to be removed..
});
Run Code Online (Sandbox Code Playgroud)