您可以将一个函数传递给 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);
});