jQuery - 为什么委托传播,即使在调用`e.preventDefault`之后? [英] jQuery - why does delegate propagate, even after `e.preventDefault` is called?

查看:94
本文介绍了jQuery - 为什么委托传播,即使在调用`e.preventDefault`之后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带嵌套链接的div。 div有一个委托处理程序'click',它会提醒Div。 div中的链接还有一个委托处理程序'click'其中 e.preventDefault警告链接之前调用(); 。当我点击链接时,我会看到Div警报和Div警报。我不清楚为什么会发生这种情况,因为我试图阻止链接点击处理程序的传播。

I have a div with a nested link. The div has a delegate handler for 'click', which alerts "Div". The link within the div also has a delegate handler for 'click' wherein e.preventDefault(); is called before alerting "Link". When I click the link, I see the "Div" alert, and the "Div" alert. I'm unclear why this is happening since I'm attempting to stop propagation from the link's click handler.

$('body').delegate('.outer', 'click', function(e){
    e.preventDefault();
    alert('Div');
});

$('body').delegate('.outer a', 'click', function(e){
    e.preventDefault();
    alert('Link');
    // Note: I've also tried returning false (vs using preventDefault), per the docs
});



HTML



HTML

<div class="outer">
    <a href="#">Click me</a>
</div>


推荐答案


  1. PreventDefault没有停止传播,它会停止采取默认操作。

  2. 返回false / stopPropagation对委派/直播事件不起作用,因为当它到达其上的元素时事件被定义,它已经传播了。它将停止传播到DOM中更高的元素,但不会阻止调用相同级别(或更低级别)的处理程序。请参阅 http://api.jquery.com/delegate 文档。


由于.live()方法在事件传播到文件顶部
后处理事件,因此无法停止传播
直播活动。类似地,.delegate()处理的事件会将
传播到它们被委派给的元素;绑定在
上的事件处理程序在调用委托事件处理程序时,DOM树中它下面的任何元素都已经被执行
。因此,这些处理程序
可能会阻止委托处理程序通过
调用event.stopPropagation()或返回false来触发。

Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will propagate to the elements to which they are delegated; event handlers bound on any elements below it in the DOM tree will already have been executed by the time the delegated event handler is called. These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false.


  • 如果您不希望运行相同级别/ DOM元素的其他处理程序,则可以使用stopImmediatePropagation。请注意,处理程序的应用顺序非常重要。

  • If you don't want the other handlers at the same level/DOM element to run, you can use stopImmediatePropagation. Note that the order in which the handlers are applied is important.

    这篇关于jQuery - 为什么委托传播,即使在调用`e.preventDefault`之后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆