事件冒泡如何处理事件? [英] How does event bubbling work on event handling?
问题描述
我已经定义了以下事件处理程序:
I have defined this event handler:
document.addEventListener("load", function(){
alert("Called on page load");
}, false);
我注意到,当布尔标志设置为false时,它不会被调用(在气泡阶段触发) 。
I noticed it does not get called when the boolean flag is set to false(fire at bubble phase). Could someone help me out on why this is the case.
推荐答案
当事件发送到元素时,它会降级文档树处于捕获阶段,直到到达目标为止。然后,如果它是冒泡事件,它就会冒泡。
When an event is being sent to an element, it descends the document tree in the capture phase until it reaches the target. Then, if it’s a bubbling event, it bubbles back up.
将事件调度到参与树的对象(例如元素)时,它也可以到达该对象祖先的事件侦听器。首先,以树顺序调用其捕获变量设置为true的所有对象的祖先事件侦听器。其次,调用对象自己的事件侦听器。最后,只有事件的bubbles属性值为true时,才再次调用对象的祖先事件侦听器,但现在是以反向树顺序调用。
When an event is dispatched to an object that participates in a tree (e.g. an element), it can reach event listeners on that object’s ancestors too. First all object’s ancestor event listeners whose capture variable is set to true are invoked, in tree order. Second, object’s own event listeners are invoked. And finally, and only if event’s bubbles attribute value is true, object’s ancestor event listeners are invoked again, but now in reverse tree order.
load
不是冒泡事件,而且-这是重要的部分-它不针对 document
。添加捕获侦听器时,实际上是从文档内容中通常会接收该事件的部分(例如脚本或图像)中获得 load
个事件。在仅包含脚本的页面上,您根本看不到监听器被调用:
load
isn’t a bubbling event, and – here’s the important part – it doesn’t target document
. When you add a capture listener, you’re really getting load
events from parts of the document’s content that normally receive the event, like scripts or images. On a page with only the script, you won’t see the listener get called at all:
<iframe srcdoc="<script>document.addEventListener('load', () => { alert('loaded'); }, true);</script>"></iframe>
在页面上有 load
在附加了侦听器后触发的事件,例如包含< style>
s的Stack Snippet,您将看到更多不止一次:
And on a page with load
events that fire after the listener is attached, like this Stack Snippet that includes <style>
s, you’ll see it more than once:
let i = 0;
document.addEventListener('load', e => {
console.log(`loaded ${++i}: ${e.target.nodeName}`);
}, true);
您可能打算向窗口
中添加非捕获的侦听器,而不是文档
,因为窗口
是接收 load
事件的东西,与 document $ c不同$ c>。 (或者您可能有其他意思。有很多方法可以解释页面加载。请参见窗口:在MDN上加载事件,详细了解
load
事件在窗口$上的含义c $ c>和其他选择(如果不是您想要的。)
You probably meant to add a non-capturing listener to window
instead of document
, because window
is something that receives a load
event, unlike document
. (Or you might have meant something else. There’s a lot of ways to interpret "page load". See Window: load event on MDN for details on what the load
event means on window
and alternatives if it wasn’t what you intended.)
window.addEventListener("load", function() {
alert("Called on page load");
}, false);
这篇关于事件冒泡如何处理事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!