javascript 如何使用 jQuery 为元素设置类?不想添加/删除类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5808430/
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
How can I set the class for an element using jQuery? Don't want to add/remove classes
提问by jbrendel
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. But jQuery apparently only allows you use addClass() or removeClass(), like so:
这只是设置类,这正是我想要的。但是我在我的页面上使用 jQuery,所以想以“jQuery 方式”来做这件事,因为混合旧样式和 jQuery 样式似乎很奇怪。但是 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? 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?
问题在于它只是向元素添加了一个类,而不是替换当前存在的类。这是否意味着我必须跟踪旧类并首先执行 removeClass() ?有没有办法告诉 jQuery 替换当前类,不管它是什么,只用一个新类替换它?
回答by kcbanner
To remove all classes from an element:
要从元素中删除所有类:
$('#foo').removeClass();
Specifying no arguments to removeClass removes all the classes. So your solution would be:
不指定 removeClass 的参数会删除所有类。所以你的解决方案是:
$('#foo').removeClass().addClass('my_class');
回答by BoltClock
回答by g.d.d.c
You could use the .attr()
function like so:
你可以.attr()
像这样使用这个函数:
$('#foo').attr('class', 'my_class');
回答by Capsule
You could use that:
你可以这样使用:
$('#foo').attr('class', 'my_class');
It will replace any class with "my_class"
它将用“my_class”替换任何类
回答by mcgrailm
$('#foo').removeClass().addClass('my_class');
回答by jbrendel
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. So, you can do:
无论如何,答案就在 removeClass() 函数中。所以,你可以这样做:
$('#foo').removeClass().addClass("my_class");
Couldn't be simpler.
不能更简单。
回答by Victor
you can try using .toggleClass()
你可以尝试使用.toggleClass()