Javascript jquery 删除一个类(如果它存在并添加一个新类)

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

jquery removing a class (if it exists and adding a new class)

javascriptjquery

提问by bba

I'm trying use jquery to remove a class from an element (not knowing ahead of time if it exists) and add a new element to replace it.

我正在尝试使用 jquery 从元素中删除一个类(不知道它是否存在提前)并添加一个新元素来替换它。

Would this be the best way (I'm skepticle because its not checking to see if the class exists before removing it):

这会是最好的方法吗(我很怀疑,因为它在删除之前没有检查该类是否存在):

$(elem).removeClass(oldClass).addClass(newClass);

thanks

谢谢

回答by Surreal Dreams

$(elem).removeClass(oldClass).addClass(newClass);

This is perfect. No need to check first; if it's there, it goes, if not, it's already gone.

太棒了。无需先检查;如果它在那里,它就会消失,如果没有,它已经消失了。

FYI, you can also toggleClass() and add/remove a class depending on if it's already there or not.

仅供参考,您还可以切换Class() 并添加/删除一个类,具体取决于它是否已经存在。

回答by Sarfraz

You can use hasClass:

您可以使用hasClass

if ($(elem).hasClass(oldClass)){
   // it has class
} else {
   // it doesn't have specified class
}

Description: Determine whether any of the matched elements are assigned the given class.

描述:确定是否有任何匹配的元素被分配给给定的类。

回答by NimChimpsky

toggleClass 

does what you would expect it to do.

做你期望它做的事情。