删除包含一组字符的类

时间:2013-04-16 13:06:04

标签: jquery css removeclass

有没有办法删除一个启动或包含已定义文本字符串的类?

我有几个类,用于开始.bg

的背景颜色覆盖
.bgwhite
.bgblue
.bgyellow

我为一个选择框设置了一个小jquery,用于添加和删除元素的修改类,在本例中是<a href id="buttontostyle">标记 我需要删除以.bg开头的这些类,同时保留另一个确定按钮大小的类  所以像这样:

    $("#buttoncolors").change(function() // buttoncolors is the select id
    {
        var valcolor = $("#buttoncolors").val();
        $("#buttontostyle").removeClass("bg" + "*");
        $("#buttontostyle").addClass(valcolor);

    });

6 个答案:

答案 0 :(得分:5)

您可以将函数传递给removeClass,它返回您要删除的类列表。在此函数中,您可以测试每个类名是否以bg开头,如果是,则将其添加到要删除的类列表中。

$("#buttoncolors").on("change", function () {
  var valcolor = $("#buttoncolors").val();

  $("#buttonstyle").removeClass(function (index, classNames) {
    var current_classes = classNames.split(" "), // change the list into an array
        classes_to_remove = []; // array of classes which are to be removed

    $.each(current_classes, function (index, class_name) {
      // if the classname begins with bg add it to the classes_to_remove array
      if (/bg.*/.test(class_name)) {
        classes_to_remove.push(class_name);
      }
    });
    // turn the array back into a string
    return classes_to_remove.join(" ");
  });

  $("#buttonstyle").addClass(valcolor);
});

演示:http://codepen.io/iblamefish/pen/EhCaH


<强>奖金

您可以通过使用命名而不是匿名函数来代替回调代码,以便您可以多次使用它。

// name the function 
function removeColorClasses (index, classNames) {
  var current_classes = classNames.split(" "), // change the list into an array
      classes_to_remove = []; // array of classes which are to be removed

  $.each(current_classes, function (index, class_name) {
    // if the classname begins with bg add it to the classes_to_remove array
    if (/bg.*/.test(class_name)) {
      classes_to_remove.push(class_name);
    }
  });
  // turn the array back into a string
  return classes_to_remove.join(" ");
}

然后你可以通过在你通常写function () { ... }

的地方传递你的名字来反复使用这个功能
// code that the dropdown box uses
$("#buttoncolors").on("change", function () {
  var valcolor = $("#buttoncolors").val();

  $("#buttonstyle").removeClass(removeColorClasses);

  $("#buttonstyle").addClass(valcolor);
});

// another example: add a new button to remove all classes using the same function
$("#buttonclear").on("click", function () {
  $("#buttonstyle").removeClass(removeColorClasses);
});

答案 1 :(得分:2)

这应该可以解决问题,同时仍然保留其他类:

var matches = $('#buttontostyle').attr('class').match(/\bbg\S+/g);
$.each(matches, function(){
    var className = this;
    $('#buttontostyle').removeClass(className.toString());
});

答案 2 :(得分:0)

试试这个 -

$('#buttontostyle:not([class^="bg"])');

答案 3 :(得分:0)

怎么样...

// remove class regex expression function
$.fn.removeClassRegEx = function(regex) {
  var classes = $(this).attr('class');
  if (!classes || !regex) return false;
  var classArray = [];
  classes = classes.split(' ');
  for (var i = 0, len = classes.length; i < len; i++)
    if (!classes[i].match(regex)) classArray.push(classes[i]);
  $(this).attr('class', classArray.join(' '));
};

// run function on #card element
$('#card').removeClassRegEx('brand-');
.card-logo {
  background: black;
  color: white;
}

.brand-mastercard {
  background: red;
}
<code id="card" class="card-logo brand-mastercard">Inspect this element</code>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

来源从这里... https://websanova.com/blog/jquery/jquery-remove-class-by-regular-expression

答案 4 :(得分:0)

允许更大的灵活性,用户只需要为要删除的每个类返回true:

$.fn.removeClassBy = function (fun) {
  if (!fun) return
  $(this).removeClass(function (index, classNames) {
    const currentClasses = classNames.split(' '); // change the list into an array
    let classesToRemove = []; // array of classes which are to be removed

    $.each(currentClasses, function (index, className) {
      // if the classname begins with bg add it to the classes_to_remove array
      if (fun(className)) {
        classesToRemove.push(className);
      }
    });
    // turn the array back into a string
    return classesToRemove.join(' ');
  })
}

用法:

$('[class*="some-partial-class-name"]').removeClassBy(className => className.includes('some-partial-class-name'));

答案 5 :(得分:-2)

试试这个

 $("#buttontostyle").removeClass('[class^="bg"]');