gpt4 book ai didi

javascript - jQuery - 为什么委托(delegate)传播,即使在调用 `e.preventDefault` 之后?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:27:23 25 4
gpt4 key购买 nike

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

JavaScript

$('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

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

最佳答案

  1. PreventDefault 不会停止传播,它会阻止执行默认操作。
  2. 返回 false/stopPropagation 对委托(delegate)/实时事件不起作用,因为当它到达定义事件的元素时,它已经向上传播了。它将停止传播到 DOM 中更高层的元素,但不会阻止调用相同层级(或更低层)的处理程序。从 http://api.jquery.com/delegate 看到这个文档。

    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.

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

  4. 您可能应该使用 on() ,而不是 jQuery 1.7 的委托(delegate)/直播。

关于javascript - jQuery - 为什么委托(delegate)传播,即使在调用 `e.preventDefault` 之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8288507/

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