有没有什么简单的方法来删除所有匹配的类,例如,
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>
谢谢!
当前回答
你也可以使用元素的DOM对象的className属性:
var $hello = $('#hello');
$('#hello').attr('class', $hello.get(0).className.replace(/\bcolor-\S+/g, ''));
其他回答
你也可以使用元素的DOM对象的className属性:
var $hello = $('#hello');
$('#hello').attr('class', $hello.get(0).className.replace(/\bcolor-\S+/g, ''));
对于jQuery插件,试试这个
$.fn.removeClassLike = function(name) {
return this.removeClass(function(index, css) {
return (css.match(new RegExp('\\b(' + name + '\\S*)\\b', 'g')) || []).join(' ');
});
};
或者这个
$.fn.removeClassLike = function(name) {
var classes = this.attr('class');
if (classes) {
classes = classes.replace(new RegExp('\\b' + name + '\\S*\\s?', 'g'), '').trim();
classes ? this.attr('class', classes) : this.removeAttr('class');
}
return this;
};
编辑:第二种方法应该快一点,因为它只在整个类字符串上运行一个regex替换。第一个(更短)使用jQuery自己的removeClass方法,该方法迭代所有现有的类名,并逐个测试给定的正则表达式,因此在底层,它为相同的工作执行了更多步骤。然而,在现实生活中,这种差异是可以忽略不计的。
速度比较基准
您也可以使用Element.classList使用普通JavaScript来实现这一点。也不需要使用正则表达式:
函数removeColorClasses(元素) { for(让数组的className从(element.classList)) 如果(className.startsWith(“颜色”)) element.classList.remove(名称); }
注意:注意我们在开始之前创建了classList的Array副本,这很重要,因为classList是一个活跃的DomTokenList,它会在类被删除时更新。
如果你只是需要去除最后一组颜色,下面的方法可能适合你。
在我的情况下,我需要在单击事件的主体标记上添加一个颜色类,并删除设置的最后一个颜色。在这种情况下,存储当前颜色,然后查找数据标记以删除最后设置的颜色。
代码:
var colorID = 'Whatever your new color is';
var bodyTag = $('body');
var prevColor = bodyTag.data('currentColor'); // get current color
bodyTag.removeClass(prevColor);
bodyTag.addClass(colorID);
bodyTag.data('currentColor',colorID); // set the new color as current
可能不是你需要的,但对我来说是,这是我看到的第一个SO问题,所以我想分享我的解决方案,以防它能帮助到任何人。
从jQuery 1.4开始,removeClass函数就带有一个函数参数。
$("#hello").removeClass (function (index, className) {
return (className.match (/(^|\s)color-\S+/g) || []).join(' ');
});
实例:http://jsfiddle.net/xa9xS/1409/