简体   繁体   English

如何在jQuery中删除带有异常的类

[英]How to removeClass with exception in jQuery

i have a little jQuery case. 我有一个小jQuery的情况。 So, i want to remove all of block classes but with little exception - if this div/block have some classes every of them will be deleated but one specify not. 因此,我想删除所有块类,但几乎没有例外-如果此div / block有一些类,则每个类都会被删除,但一个不指定。 I'v try something like this but it's not work. 我正在尝试类似的方法,但是它不起作用。

$('#rounded_items').removeClass(function(){
    $('#rounded_items').not.getElementsByClassName('small_menu');
}).addClass('main_menu');

Can you help me? 你能帮助我吗?

It's a little unclear what exactly you're trying to do, but my best guess would be something like this: 尚不清楚您到底想做什么,但我最好的猜测是这样的:

$('#rounded_items:not(.small_menu)').removeClass().addClass('main_menu');

... which will replace all class names with just main_menu to all items with ID rounded_items (!!!) except those with class small_menu . ...这将替换刚才的所有类名main_menu与ID的所有项目rounded_items (!)除了那些类small_menu

Do take note that IDs should be unique . 请注意,ID 应该是唯一的 Can't stress that enough. 不能那么强调。 So it doesn't make sense to select by ID and expect multiple elements so that you can filter by class further. 因此,按ID选择并期望多个元素没有意义,以便您可以进一步按类进行过滤。

ID's should be unique, so all you have to do is check that the single element you are targeting does not have the class before you remove the classes : ID应该是唯一的,因此您所要做的就是在删除类之前检查要定位的单个元素是否没有该类:

var isSmall = $('#rounded_items').is('.small_menu');
$('#rounded_items').attr('class', isSmall ? 'main_menu' : '');

Can't you just check if the object has this class which should not be removed. 您不能仅检查对象是否具有不应删除的此类。 If it has it - remove all classes and add the needed class. 如果有,请删除所有类并添加所需的类。 Something like this: 像这样:

if ($("#item").hasClass("neededClass")){
   $("#item").removeClass();
   $("#item").addClass("neededClass");
}

I'm not sure if this is what you want to do. 我不确定这是否是您想要的。

Use following code 使用以下代码

$('#rounded_items').removeClass(function(){
     var el = $('.small_menu');
    $('#rounded_items').not(el);
}).addClass('main_menu');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM