Mat*_*att 6 css jquery removeclass
有没有办法删除一个启动或包含已定义文本字符串的类?
我有几个类的背景颜色覆盖开始 .bg
.bgwhite
.bgblue
.bgyellow
Run Code Online (Sandbox Code Playgroud)
我为一个选择框设置了一个小jquery,它为一个元素添加和删除了修改类,在这种情况下<a href id="buttontostyle">我需要删除这些类的标记.bg,同时保留另一个确定按钮大小的类.像这样:
$("#buttoncolors").change(function() // buttoncolors is the select id
{
var valcolor = $("#buttoncolors").val();
$("#buttontostyle").removeClass("bg" + "*");
$("#buttontostyle").addClass(valcolor);
});
Run Code Online (Sandbox Code Playgroud)
您可以将函数传递给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);
});
Run Code Online (Sandbox Code Playgroud)
演示: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(" ");
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过传递其通常写入的名称来反复使用此函数 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);
});
Run Code Online (Sandbox Code Playgroud)