10

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

4

7 回答 7

17

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

$('#yourElement').attr('class',"aa dd");
于 2011-10-19T18:45:02.437 回答
9

为了让它更干净一点,你可以创建一个小扩展。

jQuery.fn.removeClassExcept = function (val) {
    return this.each(function () {
        $(this).removeClass().addClass(val);
    });
};

然后你可以像这样使用它

$("selector").removeClassExcept("aa dd");

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

更新

使用 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
    });
};
于 2011-10-19T18:47:34.267 回答
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..
});
于 2011-10-19T18:57:36.117 回答
4

您可以删除所有并添加所需的:

$('#divID').removeClass()
   .addClass('aa dd'); // add multiple classes by separating with space

注意:在removeClass()不指定特定类名的情况下调用会删除所有类。

于 2011-10-19T18:43:14.060 回答
4

jQuery 实际上为 removeClass 方法提供了一个回调参数,因此您可以使用一个简单的 javascript 正则表达式来返回除您不想删除的类之外的所有类:

$('#myDiv').removeClass(function() {
    return $(this).attr('class').replace(/aa|bb/g, '');
});

这样,如果“aa”和“bb”类尚不存在,您就不会添加它们。

你可以在这里看到它的作用:http: //jsfiddle.net/sr86u/3/

于 2011-10-19T19:25:34.993 回答
2

你可以做到的一种方法是用你想要保留的类覆盖所有类。因此,如果您的 div 的 id 为“myDiv”,那么您可以这样做:

$('#myDiv').attr('class', 'aa dd');
于 2011-10-19T18:46:28.260 回答
2

如果您知道要保留哪些课程,您可以重新添加它们(正如其他人已经展示的那样)。

我会假设不知道这些类是否已经应用,所以我会更进一步:

var keep = ['aa','bb'],  // 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
于 2011-10-19T18:47:12.877 回答