有没有什么简单的方法来删除所有匹配的类,例如,

color-*

如果我有一个元素:

<div id="hello" class="color-red color-brown foo bar"></div>

去除后,它将是

<div id="hello" class="foo bar"></div>

谢谢!


当前回答

如果你想在其他地方使用它,我建议你扩展。这个对我来说很好。

 $.fn.removeClassStartingWith = function (filter) {
    $(this).removeClass(function (index, className) {
        return (className.match(new RegExp("\\S*" + filter + "\\S*", 'g')) || []).join(' ')
    });
    return this;
};

用法:

$(".myClass").removeClassStartingWith('color');

其他回答

基于ARS81的答案(只匹配以开头的类名),这里有一个更灵活的版本。也是hasClass()正则表达式版本。

用法:$ (' .selector ') .removeClassRegex(‘\ \ S * foo [0 - 9] + ')

$.fn.removeClassRegex = function(name) {
  return this.removeClass(function(index, css) {
    return (css.match(new RegExp('\\b(' + name + ')\\b', 'g')) || []).join(' ');
  });
};

$.fn.hasClassRegex = function(name) {
  return this.attr('class').match(new RegExp('\\b(' + name + ')\\b', 'g')) !== null;
};

解决这个问题的另一种方法是使用数据属性,数据属性本质上是唯一的。

你可以像这样设置元素的颜色:$el。attr(“data-color”、“红色”);

你可以在css中设置它的样式:[data-color="red"]{color: tomato;}

这就否定了使用类的需要,这有需要删除旧类的副作用。

$('div').attr('class', function(i, c){
    return c.replace(/(^|\s)color-\S+/g, '');
});

类似于@tremby的答案,这里是@Kobi的答案作为一个插件,将匹配前缀或后缀。

ex)剥离btn-mini和btn-danger,但当stripClass(“btn-”)时不剥离btn。 当stripClass('btn', 1)剥离马btn和牛btn,但不剥离btn-mini或btn

代码:

$.fn.stripClass = function (partialMatch, endOrBegin) {
    /// <summary>
    /// The way removeClass should have been implemented -- accepts a partialMatch (like "btn-") to search on and remove
    /// </summary>
    /// <param name="partialMatch">the class partial to match against, like "btn-" to match "btn-danger btn-active" but not "btn"</param>
    /// <param name="endOrBegin">omit for beginning match; provide a 'truthy' value to only find classes ending with match</param>
    /// <returns type=""></returns>
    var x = new RegExp((!endOrBegin ? "\\b" : "\\S+") + partialMatch + "\\S*", 'g');

    // https://stackoverflow.com/a/2644364/1037948
    this.attr('class', function (i, c) {
        if (!c) return; // protect against no class
        return c.replace(x, '');
    });
    return this;
};

https://gist.github.com/zaus/6734731

我有同样的问题,并提出了以下使用下划线的_。过滤方法。一旦我发现removeClass接受一个函数并为您提供一个类名列表,就很容易将其转换为一个数组并过滤掉类名以返回到removeClass方法。

// Wildcard removeClass on 'color-*'
$('[class^="color-"]').removeClass (function (index, classes) {
  var
    classesArray = classes.split(' '),
    removeClass = _.filter(classesArray, function(className){ return className.indexOf('color-') === 0; }).toString();

  return removeClass;
});