jQuery .removeClass() 没有做任何事情的奇怪问题

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

Odd issue with jQuery .removeClass() not doing anything

jquerycssjquery-uisettimeout

提问by jbabey

I have some code that adds classes to an element and then tries to remove them and add different ones 1 second later. I'm getting some very odd behavior that I can't even reproduce in a simple jsfiddle example.

我有一些代码将类添加到元素,然后尝试删除它们并在 1 秒后添加不同的类。我得到了一些非常奇怪的行为,我什至无法在一个简单的jsfiddle 示例中重现。

Here's the relevant JavaScript code I have:

这是我拥有的相关 JavaScript 代码:

console.log('before destroyed: ' + currentTile.get(0).className);
currentTile.addClass(classes.destroyed);
console.log('after destroyed: ' + currentTile.get(0).className);

setTimeout(function () {
    console.log('before blanking: ' + currentTile.get(0).className);
    currentTile.removeClass().addClass(classes.blank + ' ui-draggable');
    console.log('after blanking: ' + currentTile.get(0).className);
}, 2000);

And here is what the console is saying:

这是控制台所说的:

enter image description here

在此处输入图片说明

As you can see, adding the destroyedclass works fine, but the call to removeClass()inside of the setTimeoutappears to be doing nothing, and then the .addClass(classes.blank + ' ui-draggable');also appears to be working fine. Also, if I pass a single class to removeClassit removes that one class without a problem.

如您所见,添加destroyed类工作正常,但对removeClass()内部的调用setTimeout似乎没有任何作用,然后.addClass(classes.blank + ' ui-draggable');似乎也工作正常。此外,如果我将单个类传递给removeClass它,则可以毫无问题地删除该类。

If it were an issue of context or currentTilebeing the wrong element, I would think the addClasswould also fail? Anyone have any idea what is going on here?

如果是上下文问题或者currentTile是错误的元素,我认为addClass这也会失败?任何人都知道这里发生了什么?

Additional info: jQuery latest (v.1.9.0 I think), jQuery UI v 1.10.0, Chrome v.24.0.1312.56 m

附加信息:jQuery 最新版(我认为是 v.1.9.0)、jQuery UI v 1.10.0、Chrome v.24.0.1312.56 m



Edit: The problem appears to be directly related to jQuery UI, and can be seen happening in this fiddle.

编辑:问题似乎与 jQuery UI 直接相关,并且可以在这个 fiddle 中看到。



Edit 2: This was confirmed as a bug in jQuery, and has been fixed.

编辑 2:这被确认为jQuery 中错误,并已修复。

采纳答案by Dom

Try using .removeAttr('class')rather than .removeClass().

尝试使用.removeAttr('class')而不是.removeClass().

DEMO:

演示:

http://jsfiddle.net/MvvmJ/8/

http://jsfiddle.net/MvvmJ/8/

Hope this helps and let me know if you have any questions!

希望这会有所帮助,如果您有任何问题,请告诉我!