jQuery 如何通过jquery更改元素的类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3959236/
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 to change class name of an element by jquery
提问by Nishant Kumar
<div class="bestAnswerControl">
<div id="ct100_contentplaceholder_lvanswer_control_divbestanswer"
class="IsBestAnswer"></div>
</div>
I want to add:
我想补充:
.bestanswer
{
// some attribute
}
I want to replace class="IsBestAnswer"
of div to class="bestanswer"
by jquery.
How do I do this?
我想用 jquery替换class="IsBestAnswer"
div class="bestanswer"
。我该怎么做呢?
I am using this approach:
我正在使用这种方法:
$('.IsBestAnswer').addclass('bestanswer');
but it's not working.
但它不起作用。
回答by Nikita Rybak
$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');
Case in method names is important, so no addclass
.
方法名称中的大小写很重要,所以没有addclass
.
回答by Tim
Instead of removeClass and addClass, you can also do it like this:
除了 removeClass 和 addClass,您还可以这样做:
$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');
回答by jensgram
$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');
Your code has two problems:
您的代码有两个问题:
- The selector
.IsBestAnswe
does not match what you thought - It's
addClass()
, notaddclass()
.
- 选择器
.IsBestAnswe
与您的想法不符 - 是
addClass()
,不是addclass()
。
Also, I'm not sure whether you want to replacethe class or addit. The above will replace, but remove the .removeClass('IsBestAnswer')
part to add only:
另外,我不确定您是要替换该类还是添加它。以上将替换,但.removeClass('IsBestAnswer')
仅删除要添加的部分:
$('.IsBestAnswer').addClass('bestanswer');
You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer
vs. bestanswer
).
你也应该决定在你的 CSS 类中是使用驼峰式还是全小写(例如bestAnswer
vs. bestanswer
)。