jQuery removeClass() 但不是某些类

发布于 2024-12-10 13:55:51 字数 172 浏览 0 评论 0原文

如何从元素中删除除某些类之外的所有类。我假设我们不能将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

别把无礼当个性 2024-12-17 13:55:51

为什么不将 class 属性替换为您想要的类,如下所示

$('#yourElement').attr('class',"aa dd");

Why don't you just replace the class attribute with the classes that you want like so

$('#yourElement').attr('class',"aa dd");
苍景流年 2024-12-17 13:55:51

为了使其更简洁,您可以创建一个小扩展。

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

一样使用它

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

然后你可以像下面的例子

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
    });
};

To make it a little cleaner, you could create a little extension.

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

Then you could use it like

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

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/

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
    });
};
夜未央樱花落 2024-12-17 13:55:51

.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..
});

.removeClass() accepts as a parameter a function that will return which classes to actually remove..

so

$('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..
});
煞人兵器 2024-12-17 13:55:51

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

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

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

You can remove all and add needed ones back:

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

Note: Calling removeClass() without specifying specific class name removes all classes.

梦旅人picnic 2024-12-17 13:55:51

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

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

这样您就不会添加类“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:

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

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/

坐在坟头思考人生 2024-12-17 13:55:51

一种方法是用您想要保留的类覆盖所有类。因此,如果您的 div 的 id 为“myDiv”,那么您可以执行以下操作:

$('#myDiv').attr('class', 'aa dd');

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:

$('#myDiv').attr('class', 'aa dd');
泼猴你往哪里跑 2024-12-17 13:55:51

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

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

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

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:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文