为什么删除className后会触发附加到className的单击事件? [英] Why is click event attached to className fired after className is removed?
问题描述
相关:双击的jquery超时
给出以下代码:
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>
fire
className
从2000ms
之后的.onlyfire
元素中删除,其中与.fire
关联的click
事件的预期结果也将不适用,因为不会出现document
中的.fire
元素.
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
.
但是,正如@ 120382833在评论
However, as pointed out @120382833 at comment
单击执行某项操作",等待2秒钟,直到执行某项操作" 返回,再次单击,它将显示警报.它不应该..它 应该再次显示轻击,并且只有在您开始的2秒钟内单击时, 警报应该显示出来.
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.
要重现
- 在
console
处检查.onlyfire
元素; - 点击
.onlyfire
元素; - 两秒钟不做任何事
- 原始文本应设置为
.onlyfire
元素; -
.fire
className
将从.onlyfire
元素中删除; - 再次单击
.onlyfire
元素
附加到 - 处理程序将被调用,依次调用
alert("this should not be showing once the text is changed back to original")
,尽管此时document
中不存在.fire
元素
.fire
元素的- Inspect
.onlyfire
element atconsole
; - click
.onlyfire
element; - do nothing for two seconds;
- the original text should be set back at
.onlyfire
element; .fire
className
will be removed from.onlyfire
element;- click
.onlyfire
element again - handler attached to
.fire
element is called, in turn callingalert("this should not be showing once the text is changed back to original")
, though no.fire
element exists indocument
at that point
问题:这是jQuery错误还是预期的行为?或者,我们是否忽略了javascript
中可以解释结果的内容?
Question: Is this a jQuery bug, or expected behaviour? Or, have we overlooked something within javascript
which would explain result?
推荐答案
这是预期的行为.
一旦附加了事件处理程序,对该元素进行的类更改就不会影响该事件将触发该事件处理程序的事实.该类仅在查找要附加处理程序的元素时起作用.完成后,类选择器将不再起作用.
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.
这篇关于为什么删除className后会触发附加到className的单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!