如何从一个元素中删除除某些类之外的所有类。 我假设我们不能在removeClass()
中使用not。 假设我有一个<div class =“aa bb cc dd ee ff”></div>
,我想删除除aa dd
之外的所有类。 我该怎么做。
如何从一个元素中删除除某些类之外的所有类。 我假设我们不能在removeClass()
中使用not。 假设我有一个<div class =“aa bb cc dd ee ff”></div>
,我想删除除aa dd
之外的所有类。 我该怎么做。
你为什么不直接用这样的方式替换class属性为你想要的类名呢?
$('#yourElement').attr('class',"aa dd");
jQuery.fn.removeClassExcept = function (val) {
return this.each(function () {
$(this).removeClass().addClass(val);
});
};
$("selector").removeClassExcept("aa dd");
jQuery.fn.removeClassExcept = function (val) {
return this.each(function (index, el) {
var keep = val.split(" "), // list we'd like to keep
reAdd = [], // ones that should be re-added if found
$el = $(el); // element we're working on
// look for which we re-add (based on them already existing)
for (var c = 0; c < keep.length; c++){
if ($el.hasClass(keep[c])) reAdd.push(keep[c]);
}
// drop all, and only add those confirmed as existing
$el
.removeClass() // remove existing classes
.addClass(reAdd.join(' ')); // re-add the confirmed ones
});
};
<div class="a b c d f">
和$('div').removeClassExcept('d e')
会添加一个从未存在过的e
类。 - Brad Christie.removeClass()
接受一个函数作为参数,该函数将返回要实际删除的类。
因此
$('div').removeClass(function(i, class){
// variable class hold the current value of the class attribute
var list = class.split(' '); // we create an array with the classes
return list.filter(function(val){ // here we remove the classes we want to keep
return (val != 'aa' && val != 'dd');
}).join(' '); // and return that list as a string which indicates the classes to be removed..
});
$('#divID').removeClass()
.addClass('aa dd'); // add multiple classes by separating with space
removeClass()
会删除所有类。jQuery提供了一个回调参数来进行removeClass方法,因此您可以使用简单的JavaScript正则表达式来返回除您不想删除的类之外的所有类:
$('#myDiv').removeClass(function() {
return $(this).attr('class').replace(/aa|bb/g, '');
});
一种方法是只使用你想要保留的类名来覆盖所有类名。所以,如果你的 div 元素有一个 id 为 "myDiv",那么你可以这样做:
$('#myDiv').attr('class', 'aa dd');
var keep = ['aa','bb'], // list we'd like to keep
reAdd = [], // ones that should be re-added if found
$el = = $(el); // element we're working on
// look for which we re-add (based on them already existing)
for (var c = 0; c < keep.length; c++){
if ($el.hasClass(keep[c])) reAdd.push(keep[c]);
}
// drop all, and only add those confirmed as existing
$el
.removeClass() // remove existing classes
.addClass(reAdd.join(' ')); // re-add the confirmed ones