javascript jquery removeClass() 不删除所有类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16355332/
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
jquery removeClass() not removing all classes
提问by mises
I have an element like this:
我有一个这样的元素:
<div class="one two three" id="waterhorse">horse</div>
When I run this code in the browser console:
当我在浏览器控制台中运行此代码时:
$("#waterhorse").removeClass();
I get this:
我明白了:
[<div id=?"waterhorse" class=?"one two three">?horse?</div>?]
In other words, it doesn't work; it doesn't remove any classes on the element. I unfortunately can't reproduce it in jsfiddle.
换句话说,它不起作用;它不会删除元素上的任何类。不幸的是,我无法在 jsfiddle 中重现它。
However, I can remove a specific class:
但是,我可以删除特定的类:
$("#waterhorse").removeClass("two");
Also, this will remove all classes:
此外,这将删除所有类:
$("#waterhorse").removeAttr("class");
Any idea why the latter works to remove all classes, but the former doesn't?
知道为什么后者可以删除所有类,而前者不能吗?
回答by Ben Mills
Seems like this is a known problem with jQuery and jQueryUI not playing nicely together:
似乎这是 jQuery 和 jQueryUI 不能很好地协同工作的一个已知问题:
Odd issue with jQuery .removeClass() not doing anything
jQuery .removeClass() 没有做任何事情的奇怪问题
http://bugs.jqueryui.com/ticket/9015
http://bugs.jqueryui.com/ticket/9015
The answer above is a workaround that uses .removeAttr('class')
instead of .removeClass()
上面的答案是使用.removeAttr('class')
而不是.removeClass()
回答by MMeersseman
If we read the documentationit states this:
如果我们阅读文档,它会指出:
If a class name is included as a parameter, then only that class will be removed from the set of matched elements. If no class names are specified in the parameter, all classes will be removed.
如果类名作为参数包含在内,则只会从匹配的元素集中删除该类。如果参数中未指定类名,则将删除所有类。
In other words, .removeClass()
should work without parameters. I've tried this in FF and this works as intended.
换句话说,.removeClass()
应该在没有参数的情况下工作。我已经在 FF 中尝试过这个,并且按预期工作。
I tried to reproduce the problem you are experiencing, but it couldn't do it: jsFiddle
我试图重现您遇到的问题,但它无法做到:jsFiddle
<div class="one two three" id="waterhorse">horse</div>
$("#waterhorse").removeClass();
$("#waterhorse").addClass("four");
console.log($("#waterhorse"));
What browser version are you using?
您使用的是什么浏览器版本?
回答by Surama Hotta
You can do this in $(document).ready() to achieve this.
您可以在 $(document).ready() 中执行此操作以实现此目的。
$("#waterhorse").attr("class", "");
or
$("#waterhorse").removeClass();
Hope this will help you.:)
希望能帮到你。:)