有没有什么简单的方法来删除所有匹配的类,例如,
color-*
如果我有一个元素:
<div id="hello" class="color-red color-brown foo bar"></div>
去除后,它将是
<div id="hello" class="foo bar"></div>
谢谢!
有没有什么简单的方法来删除所有匹配的类,例如,
color-*
如果我有一个元素:
<div id="hello" class="color-red color-brown foo bar"></div>
去除后,它将是
<div id="hello" class="foo bar"></div>
谢谢!
当前回答
您也可以使用Element.classList使用普通JavaScript来实现这一点。也不需要使用正则表达式:
函数removeColorClasses(元素) { for(让数组的className从(element.classList)) 如果(className.startsWith(“颜色”)) element.classList.remove(名称); }
注意:注意我们在开始之前创建了classList的Array副本,这很重要,因为classList是一个活跃的DomTokenList,它会在类被删除时更新。
其他回答
您也可以使用Element.classList使用普通JavaScript来实现这一点。也不需要使用正则表达式:
函数removeColorClasses(元素) { for(让数组的className从(element.classList)) 如果(className.startsWith(“颜色”)) element.classList.remove(名称); }
注意:注意我们在开始之前创建了classList的Array副本,这很重要,因为classList是一个活跃的DomTokenList,它会在类被删除时更新。
类似于@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
删除任何以begin开头的类的泛型函数:
function removeClassStartingWith(node, begin) {
node.removeClass (function (index, className) {
return (className.match ( new RegExp("\\b"+begin+"\\S+", "g") ) || []).join(' ');
});
}
http://jsfiddle.net/xa9xS/2900/
Var begin = 'color-'; 函数removeClassStartingWith(node, begin) { 节点。removeClass(函数(索引,className) { 返回(类名。(新RegExp匹配(“\ \ b”+ +“\ \ S +”开始,“g ") ) || []).加入(' '); }); } removeClassStartingWith($(' #你好'),“颜色——”); console.log($(" #你好”)[0].className); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <div id="hello" class="color-red - color-brown foo bar"></div>
你也可以使用元素的DOM对象的className属性:
var $hello = $('#hello');
$('#hello').attr('class', $hello.get(0).className.replace(/\bcolor-\S+/g, ''));
解决这个问题的另一种方法是使用数据属性,数据属性本质上是唯一的。
你可以像这样设置元素的颜色:$el。attr(“data-color”、“红色”);
你可以在css中设置它的样式:[data-color="red"]{color: tomato;}
这就否定了使用类的需要,这有需要删除旧类的副作用。