jQuery removeClass 通配符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2644299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery removeClass wildcard
提问by atp
Is there any easy way to remove all classes matching, for example,
有没有什么简单的方法可以删除所有匹配的类,例如,
color-*
so if I have an element:
所以如果我有一个元素:
<div id="hello" class="color-red color-brown foo bar"></div>
after removing, it would be
去掉后就是
<div id="hello" class="foo bar"></div>
Thanks!
谢谢!
回答by jimmystormig
The removeClassfunction takes a function argument since jQuery 1.4.
从jQuery 1.4 开始,removeClass函数接受一个函数参数。
$("#hello").removeClass (function (index, className) {
return (className.match (/(^|\s)color-\S+/g) || []).join(' ');
});
Live example: http://jsfiddle.net/xa9xS/1409/
回答by Kobi
$('div').attr('class', function(i, c){
return c.replace(/(^|\s)color-\S+/g, '');
});
回答by Pete B
I've written a plugin that does this called alterClass – Remove element classes with wildcard matching. Optionally add classes: https://gist.github.com/1517285
我编写了一个插件来执行此操作,称为 alterClass – 删除具有通配符匹配的元素类。可选地添加类:https: //gist.github.com/1517285
$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
回答by tremby
I've generalized this into a Jquery plugin which takes a regex as an argument.
我已将其概括为一个 Jquery 插件,该插件以正则表达式为参数。
Coffee:
咖啡:
$.fn.removeClassRegex = (regex) ->
$(@).removeClass (index, classes) ->
classes.split(/\s+/).filter (c) ->
regex.test c
.join ' '
Javascript:
Javascript:
$.fn.removeClassRegex = function(regex) {
return $(this).removeClass(function(index, classes) {
return classes.split(/\s+/).filter(function(c) {
return regex.test(c);
}).join(' ');
});
};
So, for this case, usage would be (both Coffee and Javascript):
因此,对于这种情况,用法将是(Coffee 和 Javascript):
$('#hello').removeClassRegex(/^color-/)
Note that I'm using the Array.filter
function which doesn't exist in IE<9. You could use Underscore's filter functioninstead or Google for a polyfill like this WTFPL one.
请注意,我正在使用Array.filter
IE<9 中不存在的函数。您可以使用Underscore 的过滤器功能,或者使用 Google 来实现像WTFPL one 这样的 polyfill。
回答by Charly Guirao
If you want to use it in other places I suggest you an extension. This one is working fine for me.
如果你想在其他地方使用它,我建议你扩展。这个对我来说很好用。
$.fn.removeClassStartingWith = function (filter) {
$(this).removeClass(function (index, className) {
return (className.match(new RegExp("\S*" + filter + "\S*", 'g')) || []).join(' ')
});
return this;
};
Usage:
用法:
$(".myClass").removeClassStartingWith('color');
回答by meni181818
we can get all the classes by .attr("class")
, and to Array, And loop & filter:
我们可以通过.attr("class")
, 和 Array获取所有类,以及循环和过滤器:
var classArr = $("#sample").attr("class").split(" ")
$("#sample").attr("class", "")
for(var i = 0; i < classArr.length; i ++) {
// some condition/filter
if(classArr[i].substr(0, 5) != "color") {
$("#sample").addClass(classArr[i]);
}
}
回答by drzaus
Similar to @tremby's answer, here is @Kobi's answeras a plugin that will match either prefixes or suffixes.
与@tremby's answer类似,这里是@Kobi's answer作为一个插件,将匹配前缀或后缀。
- ex) strips
btn-mini
andbtn-danger
but notbtn
whenstripClass("btn-")
. - ex) strips
horsebtn
andcowbtn
but notbtn-mini
orbtn
whenstripClass('btn', 1)
- 例如)条带
btn-mini
,btn-danger
但不是btn
whenstripClass("btn-")
。 - EX)条
horsebtn
和cowbtn
,但不会btn-mini
或btn
何时stripClass('btn', 1)
Code:
代码:
$.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;
};
回答by nynyny
I had the same issue and came up with the following that uses underscore's _.filter method. Once I discovered that removeClass takes a function and provides you with a list of classnames, it was easy to turn that into an array and filter out the classname to return back to the removeClass method.
我遇到了同样的问题,并提出了以下使用下划线的 _.filter 方法的问题。一旦我发现 removeClass 接受一个函数并为您提供一个类名列表,很容易将它转换为一个数组并过滤掉类名以返回给 removeClass 方法。
// Wildcard removeClass on 'color-*'
$('[class^="color-"]').removeClass (function (index, classes) {
var
classesArray = classes.split(' '),
removeClass = _.filter(classesArray, function(className){ return className.indexOf('color-') === 0; }).toString();
return removeClass;
});
回答by ARS81
For a jQuery plugin try this
对于 jQuery 插件试试这个
$.fn.removeClassLike = function(name) {
return this.removeClass(function(index, css) {
return (css.match(new RegExp('\b(' + name + '\S*)\b', 'g')) || []).join(' ');
});
};
or this
或这个
$.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;
};
回答by kzar
You could also do this with vanilla JavaScript using Element.classList. No need for using a regular expression either:
您也可以使用Element.classList使用 vanilla JavaScript 执行此操作。也不需要使用正则表达式:
function removeColorClasses(element)
{
for (let className of Array.from(element.classList))
if (className.startsWith("color-"))
element.classList.remove(className);
}
function removeColorClasses(element)
{
for (let className of Array.from(element.classList))
if (className.startsWith("color-"))
element.classList.remove(className);
}
Note: Notice that we create an Array
copy of the classList
before starting, that's important since classList
is a live DomTokenList
which will update as classes are removed.
注:请注意,我们创建一个Array
副本classList
开始之前,这是重要的,因为classList
是活DomTokenList
的类被删除,这将更新。