有没有什么简单的方法来删除所有匹配的类,例如,
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>
谢谢!
当前回答
我已经写了一个插件,做这个叫做alterClass -删除元素类通配符匹配。可选地添加类:https://gist.github.com/1517285
$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
其他回答
如果你想在其他地方使用它,我建议你扩展。这个对我来说很好。
$.fn.removeClassStartingWith = function (filter) {
$(this).removeClass(function (index, className) {
return (className.match(new RegExp("\\S*" + filter + "\\S*", 'g')) || []).join(' ')
});
return this;
};
用法:
$(".myClass").removeClassStartingWith('color');
我把它概括成一个Jquery插件,它把一个正则表达式作为参数。
咖啡:
$.fn.removeClassRegex = (regex) ->
$(@).removeClass (index, classes) ->
classes.split(/\s+/).filter (c) ->
regex.test c
.join ' '
Javascript:
$.fn.removeClassRegex = function(regex) {
return $(this).removeClass(function(index, classes) {
return classes.split(/\s+/).filter(function(c) {
return regex.test(c);
}).join(' ');
});
};
因此,在这种情况下,使用将是(咖啡和Javascript):
$('#hello').removeClassRegex(/^color-/)
注意,我使用的是数组。在IE<9中不存在的过滤器函数。您可以使用下划线的过滤器函数代替或谷歌的polyfill像WTFPL一个。
解决这个问题的另一种方法是使用数据属性,数据属性本质上是唯一的。
你可以像这样设置元素的颜色:$el。attr(“data-color”、“红色”);
你可以在css中设置它的样式:[data-color="red"]{color: tomato;}
这就否定了使用类的需要,这有需要删除旧类的副作用。
$('div').attr('class', function(i, c){
return c.replace(/(^|\s)color-\S+/g, '');
});
如果你有多个元素的类名为“example”,要删除所有的“color-”类,你可以这样做:
var objs = $('html').find('.example');
for(index=0 ; index < obj1s.length ; index++){
objs[index].className = objs[index].className.replace(/col-[a-z1-9\-]*/,'');
}
如果你不把[a-z1-9-]*放在你的正则表达式中,它不会删除名字中有数字或一些“-”的类。