【发布时间】:2015-12-08 00:38:24
【问题描述】:
// Example A
$("#delegate").on("click", function(event) {
// executes on click on any descendant of #delegate or self (not a delegate at all)
// 'this' is #delegate
});
// Example B
$("#delegate").on("click", "#outer", function(event) {
// executes on click on any descendant of #outer or self
// 'this' is #outer or #inner (depends on the actual click)
});
$("#delegate").on("click", "#inner", function(event) {
// executes on click on any descendant of #inner or self (nothing happens when clicking #outer)
// 'this' is #inner
});
// Example C (now it's getting weird)
$("#delegate").on("click", "div", function(event) {
// executes twice, when clicking #inner, because the event passes #outer when bubbling up
// one time 'this' is #inner, and the other time 'this' is #outer
// stopPropagation() // actually prevents the second execution
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="delegate">
<div id="outer">
outer
<div id="inner">
inner
</div>
</div>
</div>
你如何从逻辑上解释这种行为?
恰好有一个点击事件,从#inner开始,经过#outer冒泡,最后到达#delegate。
#delegate 的 on-handler (准确地)捕获了一次事件。处理程序检查事件的历史记录是否包含任何 div 元素。
如果适用,回调函数应该被调用一次。这就是我所期望的。 “单个事件,单个处理程序,单个条件,单个回调”。
如果你看一下stopPropagation() 的行为,它会变得更加疯狂。您实际上可以避免第二次执行,尽管事件已经到达#delegate。 stopPropagation(不应该在这里工作。
on-delegation 逻辑的实现有什么“魔法”?事件冒泡和程序流是否以任何方式分开?
请不要一开始就发布“实用建议”(“改用 xyz!”)。我想了解为什么代码会以它的方式工作。
【问题讨论】:
-
您在第二次和第三次通话中错过了
click事件。 -
您是否只询问最后一种情况,委托给
div? -
谢谢。我刚刚将点击事件添加到我的帖子中。是的:基本上我只是在问最后一个案例。
-
您的问题是什么? “你如何从逻辑上解释这种行为?”好吧,
#delegate中有两个<div>s,并且将一个单击事件附加到其中的所有 div 将因此在单击#inner时触发 2 个事件。当然使用 stopPropagation 可以防止从#inner冒泡到#outer -
所以事件不会冒泡到#delegate 然后执行回调? Instad 处理程序/回调实际上附加到特定的 div?
标签: javascript jquery jquery-events delegation event-bubbling