event.stopPropagation()和event.stopImmediatePropagation()之间有什么区别?


当前回答

令人惊讶的是,所有其他答案都只说了一半事实或实际上是错误的!

e.s stopimmediatepropagation()停止为该事件调用任何进一步的处理程序,没有异常 e.s stoppropagation()类似,但如果尚未调用,仍然调用此元素上此阶段的所有处理程序

什么阶段?

例如,一个点击事件总是首先沿着DOM向下走(称为“捕获阶段”),最后到达事件的起源(“目标阶段”),然后再次冒泡(“冒泡阶段”)。使用addEventListener(),您可以分别为捕获阶段和冒泡阶段注册多个处理程序。(目标阶段在目标上调用这两种类型的处理程序,没有区别。)

这是其他答案的错误之处:

quote: “event.stopPropagation() allows other handlers on the same element to be executed” correction: if stopped in the capture phase, bubble phase handlers will never be reached, also skipping them on the same element quote: “event.stopPropagation() [...] is used to stop executions of its corresponding parent handler only” correction: if propagation is stopped in the capture phase, handlers on any children, including the target aren’t called either, not only parents ...and: if propagation is stopped in the bubble phase, all capture phase handlers have already been called, including those on parents

一个小提琴和mozilla.org事件阶段解释与演示。

其他回答

事件。stopPropagation将阻止父元素上的处理程序运行。 调用的事件。stopImmediatePropagation还将阻止同一元素上的其他处理程序运行。

jQuery API:

除了保留任何额外 元素的处理程序 执行后,此方法还将停止 通过隐式调用 event.stopPropagation()。简单地 防止事件冒泡到 祖先元素但允许其他元素 执行相同的事件处理程序 元素,我们可以使用 event.stopPropagation()。 使用 event.isImmediatePropagationStopped () 想知道这种方法是否曾经 调用(在该事件对象上)。

简而言之:event. stoppropagation()允许同一元素上的其他处理程序被执行,而event. stopimmediatepropagation()阻止每个事件运行。

我是一个后来者,但也许我可以用一个具体的例子来说明:

比如说,如果你有一个<表>,有<tr>和<td>。现在,假设你为<td>元素设置了3个事件处理程序,那么如果你在为<td>设置的第一个事件处理程序中执行event. stoppropagation(),那么<td>的所有事件处理程序仍将运行,但事件不会传播到<tr>或<表>(并且不会向上传播到<body>, <html>,文档和窗口)。

然而,现在,如果你在你的第一个事件处理程序中使用event. stopimmediatepropagation(),那么,<td>的其他两个事件处理程序将不会运行,并且不会传播到<tr>, <表>(并且不会向上和向上到<body>, <html>,文档和窗口)。

注意,它不仅仅适用于<td>。对于其他元素,它将遵循相同的原则。

event. stoppropagation()允许执行同一元素上的其他处理程序,而event. stopimmediatepropagation()阻止运行每个事件。例如下面的jQuery代码块。

$("p").click(function(event)
{ event.stopImmediatePropagation();
});
$("p").click(function(event)
{ // This function won't be executed 
$(this).css("color", "#fff7e3");
});

如果事件。stopPropagation在前面的例子中使用,然后在p元素上的下一个点击事件改变css将触发,但在case event. stopimmediatepropagation()中,下一个p点击事件将不会触发。

stopPropagation将阻止任何父处理程序被执行。stopImmediatePropagation将阻止任何父处理程序和任何其他处理程序被执行

jquery文档中的快速示例:

美元(p) .click(函数(事件){ event.stopImmediatePropagation (); }); 美元(p) .click(函数(事件){ //该函数不会被执行 (美元). css(“背景颜色”,“# f00”); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> < p > < / p >例子

注意,事件绑定的顺序在这里很重要!

美元(p) .click(函数(事件){ //该函数将被触发 (美元). css(“背景颜色”,“# f00”); }); 美元(p) .click(函数(事件){ event.stopImmediatePropagation (); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> < p > < / p >例子