gpt4 book ai didi

javascript - 使用直接事件监听器删除项目时,事件停止冒泡到委托(delegate)事件

转载 作者:行者123 更新时间:2023-12-03 11:48:00 25 4
gpt4 key购买 nike

使用 jquery 事件进行实验。

看起来,如果我在其自己的事件处理程序中删除一个项目,它会阻止事件冒泡到委托(delegate)事件,但直接绑定(bind)的事件仍然会触发。

但是,如果我在委托(delegate)事件中删除它,该事件就会像我预期的那样传播。

由于我没有返回 false 或使用 stopPropagation(),因此我认为其他事件仍然会触发,无论它们是直接绑定(bind)还是委托(delegate)。

这有道理吗?这是 jQuery 的错误吗?寻找其行为原因的解释。

这是 fiddle : http://jsfiddle.net/ahhgu1bb/

当您单击蓝点时,“A UP ...”永远不会出现在控制台中。

当您单击绿点时,它就会执行。

代码:

HTML:

<div class="main-background">
<div class="inner-area">
<div class="blue-point"></div>
<div class="green-point"></div>
</div>
</div>

javascript/jquery:

$('.main-background').on('mousedown', '.inner-area', function(e) {
console.log('A DOWN - deletegated inner-area mouse down');
});

$('.main-background').on('mouseup', '.inner-area', function(e) {
console.log('A UP - deletegated inner-area mouse up');
});

$('.main-background').on('mouseup', function(e) {
console.log('B UP - direct inner-area mouse up');
});

$('.blue-point').on('mouseup', function(e) {
console.log('C UP - direct point mouse up');
$(this).remove();
});

$('.main-background').on('mouseup', '.green-point', function(e) {
console.log('D UP - delegated point mouse up');
$(this).remove();
});

最佳答案

来自 jQuery 文档: http://api.jquery.com/on/

对于委托(delegate)事件:

... The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

因此,如果我使用事件委托(delegate),该事件实际上并不直接绑定(bind)到附加元素,而是仅通过从目标元素冒泡而触发。

因此,在我的例子中,由于目标元素在冒泡开始之前被删除,所以冒泡不会发生(感谢 Amin Jafari!),因此委托(delegate)事件永远不会触发。但任何直接绑定(bind)的事件处理程序都会被触发。

关于javascript - 使用直接事件监听器删除项目时,事件停止冒泡到委托(delegate)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25963073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com