简体   繁体   English

如何使用jQuery为元素设置类?不想添加/删除类

[英]How can I set the class for an element using jQuery? Don't want to add/remove classes

I need to set the class for an element in my page. 我需要在页面中为元素设置类。 With plain JavaScript, I would write something like: 使用纯JavaScript,我会写如下:

document.getElementById('foo').className = "my_class";

This just sets the class, which is exactly what I want. 这只是设置了类,这正是我想要的。 But I'm using jQuery on my page and so would like to do this in a "jQuery way", since it seems weird to mix the old style and the jQuery style. 但我在我的页面上使用jQuery,因此想以“jQuery方式”执行此操作,因为混合旧样式和jQuery样式似乎很奇怪。 But jQuery apparently only allows you use addClass() or removeClass(), like so: 但是jQuery显然只允许你使用addClass()或removeClass(),如下所示:

$('#foo').addClass("my_class");

The problem is that it merely adds a class to the element, it does not replace the currently existing class. 问题是它只是向元素添加一个类,它不会替换当前存在的类。 Does this mean I have to keep track of the old class and do a removeClass() first? 这是否意味着我必须先跟踪旧类并首先执行removeClass()? Is there no way to tell jQuery to replace the current class no matter what it is and just replace it with a new one? 有没有办法告诉jQuery替换当前的类,无论它是什么,只是用一个新的替换它?

To remove all classes from an element: 要从元素中删除所有类:

$('#foo').removeClass();

Specifying no arguments to removeClass removes all the classes. 不指定removeClass参数会删除所有类。 So your solution would be: 所以你的解决方案是:

$('#foo').removeClass().addClass('my_class');

使用.attr()直接设置class属性:

$('#foo').attr('class', 'my_class');

您可以像这样使用.attr()函数:

$('#foo').attr('class', 'my_class');

You could use that: 你可以用它:

$('#foo').attr('class', 'my_class');

It will replace any class with "my_class" 它将用“my_class”替换任何类

 $('#foo').removeClass().addClass('my_class');

Ah, found the answer just seconds after I posted the question. 啊,在我发布问题后几秒钟找到答案。 Apparently my Google skills were insufficient... :-( 显然我的谷歌技能不足...... :-(

At any rate, the answer is in the removeClass() function. 无论如何,答案在removeClass()函数中。 So, you can do: 所以,你可以这样做:

$('#foo').removeClass().addClass("my_class");

Couldn't be simpler. 不可能更简单。

你可以尝试使用.toggleClass()

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

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