可以传递到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
BONUS
您可以通过使用neaten了代码命名,而不是回调的匿名功能,使您可以使用它不止一次。
// 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);
});
使用REG EXP来确定开始模式的类名,并使用其删除删除()从jquery – dreamweiver
重复http://stackoverflow.com/questions/57812/remove-all-classes-that-begin-with-a-certain-string – billyonecan
@billyonecan谢谢! – onebitrocket