如何使用 jquery 覆盖类

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

How to override a class using jquery

jquerycssjquery-uijquery-selectors

提问by Hulk

A jQuery CSS class sets the following:

jQuery CSS 类设置以下内容:

 .newwidget { border: 1px solid #5a9ee9; background: #5a9ee9 url(t6.gif) 50% 50% repeat-x; color: #ffffff; font-weight: bold; text-transform: uppercase; padding:3px 3px 3px 10px; font-size:10px}

How can this class be overridden and a new class added so that I can put different styles in it? Maybe I have to remove before classes before adding them. How is this done?

如何覆盖这个类并添加一个新类以便我可以在其中放置不同的样式?也许我必须在添加它们之前删除它们。这是怎么做的?

Thanks

谢谢

回答by tvanfosson

Use the class selector with addClass and removeClass.

将类选择器与 addClass 和 removeClass 一起使用。

$('.newwidget').removeClass('newwidget').addClass('newerwidget');

回答by Tom Rossi

I think it's worth noting that you can remove allthe classes by leaving off the parameter from removeClass():

我认为值得注意的是,您可以通过从以下位置删除参数来删除所有removeClass()

$('.newwidget').removeClass().addClass('newerwidget');

回答by Aaron

jQuery defines addClass()and removeClass()for just this purpose:

jQuery 定义addClass()removeClass()仅用于此目的:

$("#ElementId").removeClass('oldClassName').addClass('newClassName');

The two function do the obvious. Chain them like this to change the class all in one action.

这两个功能很明显。像这样链接它们以在一个动作中改变班级。

If you would like to change all elements from 'oldClass' to 'newClass', you can use a selector like this:

如果您想将所有元素从 'oldClass' 更改为 'newClass',您可以使用这样的选择器:

$(".oldClassName").removeClass('oldClassName').addClass('newClassName');

回答by nickf

You can to removethe old class and adda new one:

您可以删除旧类并添加一个新类:

$myJQObject.removeClass('newwidget').addClass('newclass');

回答by x4tje

$(this).removeClass('oldClass').addClass('newClass');

回答by CAOakley

If you're looking to completely replace the existing classes on an element, you can use the .attr() method.

如果您希望完全替换元素上的现有类,可以使用 .attr() 方法。

$('#elementId').attr('class', 'newClassName');

Any classes on elementId will be replaced.

elementId 上的任何类都将被替换。