Javascript 在 jQuery 中添加和删除多个类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7185709/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:15:10  来源:igfitidea点击:

Add and remove multiple classes in jQuery

javascriptjquery

提问by Raman

I'm trying to add and remove multiple classes on a text field by clicking different radio buttons. I'm not able to remove the unwanted classes while switching between different radio buttons.

我试图通过单击不同的单选按钮在文本字段上添加和删除多个类。在不同的单选按钮之间切换时,我无法删除不需要的类。

My code for this is:

我的代码是:

// For 1st radio button
if (actionUrl == "search-client-by-id") {
    $("#req").removeClass("validate[required,custom[onlyLetterNumber],maxSize[20],custom[onlyLetterSp]]")
             .addClass("validate[required,custom[onlyNumberSp]]");
}
// For 2nd radio button
else if (actionUrl == "search-client-by-name") {    
    $("#req").removeClass("validate[required,custom[onlyNumberSp]]")
             .addClass("validate[required,custom[onlyLetterNumber],maxSize[20],custom[onlyLetterSp]]");
}

回答by Headshota

You can separate multiple classes with the space:

您可以使用空格分隔多个类:

$("p").addClass("myClass yourClass");

http://api.jquery.com/addClass/

http://api.jquery.com/addClass/

回答by Andrea_dev

Add multiple classes:

添加多个类:

$("p").addClass("class1 class2 class3");

or in cascade:

或级联:

$("p").addClass("class1").addClass("class2").addClass("class3");

Very similar also to remove more classes:

非常相似也删除更多类:

$("p").removeClass("class1 class2 class3");

or in cascade:

或级联:

$("p").removeClass("class1").removeClass("class2").removeClass("class3");

回答by argoden

easiest way to append class name using javascript. It can be useful when .siblings()are misbehaving.

使用 javascript 附加类名的最简单方法。它在.siblings()行为不端时很有用。

document.getElementById('myId').className += ' active';