[英]Why is click event attached to className fired after className is removed?
Related: Jquery timeout for doubleclick 相关: DoubleClick的jQuery超时
Given this code: 给出以下代码:
function handleClick() { var div = $(this); var original = $(this).html(); div.html("Tap again"); $(".onlyfire").addClass("fire").off("click"); $(".fire").one("click", function(fire) { alert("this should not be showing once the text is changed back to original"); $(this).off("click") }); setTimeout(function() { $(div).html(original); $(".onlyfire").removeClass("fire").click(handleClick); }, 2000); } function onlyfire() { $(".onlyfire").click(handleClick); }; onlyfire();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <div class="onlyfire"> Do Something </div>
the fire
className
is removed from .onlyfire
element following 2000ms
, where expected result is for click
event which was attached to .fire
would also be rendered inapplicable, as there would not be a .fire
element within document
. 在.onlyfire
2000ms
,将从.onlyfire
元素中删除fire
className
,因为附加到.fire
click
事件的预期结果也将不适用,因为document
不会包含.fire
元素。
However, as pointed out @120382833 at comment 但是,正如@ 120382833在评论中指出
Click on Do something, wait for 2 seconds until the Do Something is back, Click again and it will show the alert.. And it shouldn't.. It should display tap again and only if you click in first 2 seconds the alert should show up. 单击“执行某项操作”,等待2秒钟,直到“执行某项操作”返回,再单击一次,它将显示警报。并且它不应该。出现。
To reproduce 重现
.onlyfire
element at console
; 在console
检查.onlyfire
元素; .onlyfire
element; 单击.onlyfire
元素; .onlyfire
element; 原始文本应重新设置为.onlyfire
元素; .fire
className
will be removed from .onlyfire
element; .fire
className
将从.onlyfire
元素中删除; .onlyfire
element again 再次单击.onlyfire
元素 .fire
element is called, in turn calling alert("this should not be showing once the text is changed back to original")
, though no .fire
element exists in document
at that point 附加到.fire
元素的处理程序将被调用,依次调用alert("this should not be showing once the text is changed back to original")
,尽管.fire
document
中不存在.fire
元素 Question: Is this a jQuery bug, or expected behaviour? 问题:这是jQuery错误还是预期行为? Or, have we overlooked something within javascript
which would explain result? 或者,我们是否忽略了javascript
中可以解释结果的内容?
Event handlers are bound to elements not to their classNames. 事件处理程序绑定到元素,而不绑定到其className。 Static event handlers do not work like delegated event handlers. 静态事件处理程序不能像委托事件处理程序那样工作。
That is expected behaviour. 这是预期的行为。
Once an event handler is attached, the class changes made to that element do not influence the fact that the event will trigger the event handler. 附加事件处理程序后,对该元素进行的类更改不会影响该事件将触发该事件处理程序的事实。 The class only plays a role in finding the element to attach the handler to. 该类仅在查找要附加处理程序的元素时起作用。 Once that is done, the class selector plays no role any more. 完成后,类选择器不再起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.