Javascript 为什么在这个简单的 addEventListener 函数之后使用“false”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5657292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:18:53  来源:igfitidea点击:

Why is 'false' used after this simple addEventListener function?

javascript

提问by 0x499602D2

What is the false for at the end? Thanks.

最后的错误是什么?谢谢。

window.addEventListener('load', function() {
  alert("All done");
}, false);

采纳答案by Lucas Jones

According to MDN Web Docs, the third parameter is:

根据MDN Web Docs,第三个参数是:

useCapture
If true, useCaptureindicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listenerbefore being dispatched to any EventTargets beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Eventsfor a detailed explanation.

useCapture
If trueuseCapture表示用户希望启动捕获。启动捕获后,指定类型的所有事件将被分派到注册的,listener然后再分派到EventTargetDOM 树中它下面的任何s。通过树向上冒泡的事件不会触发指定使用捕获的侦听器。有关 详细说明,请参阅DOM Level 3 Events

回答by libra

I checked MDN too, but I still didn't understand what the useCapturewas for, so this answer is for those who still don't get it after having checked the official documentation.

我也检查了 MDN,但我仍然不明白它的useCapture用途,所以这个答案是为那些在检查了官方文档后仍然没有得到它的人准备的。

So first of all, the following happens in almost all browers:

首先,几乎所有浏览器都会发生以下情况:

In all browsers, except IE<9, there are two stages of event processing.

The event first goes down - that's called capturing, and then bubbles up. This behavior is standartized in W3C specification.

在所有浏览器中,除了 IE<9,事件处理有两个阶段。

事件首先下降 - 这称为捕获,然后冒泡。此行为在 W3C 规范中标准化。

which means no matter what you set the useCaptureto, these two event phases always exist.

这意味着无论您设置什么useCapture,这两个事件阶段始终存在。

This picture shows how it works.

这张图展示了它是如何工作的。

enter image description here

在此处输入图片说明

According to this model, the event:

Captures down - through 1 -> 2 -> 3.

Bubbles up - through 3 -> 2 -> 1.

根据这个模型,事件:

向下捕获 - 通过 1 -> 2 -> 3。

冒泡 - 通过 3 -> 2 -> 1。

Then comes your question. The 3rd param called useCaptureindicates on which of the two phases you want your handler to handle the event.

那么你的问题来了。调用的第三个参数useCapture指示您希望处理程序在两个阶段中的哪个阶段处理事件。

useCapture = true

The handler is set on the capturing phase. Events will get to it before getting to its children.

useCapture = false.

The handler is set on the bubbling phase. Events will get to it after getting to its children.

useCapture = true

处理程序设置在捕获阶段。事件会在到达它的孩子之前到达它。

useCapture = false.

处理程序设置在冒泡阶段。事件将在到达它的孩子之后到达它。

which means that if you write code like this:

这意味着如果你写这样的代码:

child.addEventListener("click", second);
parent.addEventListener("click", first, true);

when clicking child element, firstmethod will be called before second.

单击子元素时,first方法将在 之前调用second

By default, the useCaptureflag is set to falsewhich means you handler will only be called during event bubblingphase.

默认情况下,该useCapture标志设置为false,这意味着您的处理程序只会在事件冒泡阶段被调用。

For detailed info, click this reference linkand this.

有关详细信息,请单击此参考链接

回答by user10089632

@Libra's answer is very good, there just happen to be some people like me who understand better the interaction of the code with the machine.
So the following script should be explaining the event propagation. What I'm trying to do based this description schemais :
Following event flow down and up the following hierarchy :

@Libra 的回答很好,正好有像我这样的人更了解代码与机器的交互。
所以下面的脚本应该解释事件传播。基于此描述架构,我试图做的是:
按照以下层次结构向下和向上的事件流:

<window>
<document>
<body>
<section>
<div>
<paragraph>
<span>

For the sake of simplicity we'll start at the body down to the span element registering handlers for the capturing phase, and back up to the body element registering handlers for the bubbling phase. So the result would be node by node the direction taken by the event from the start to the end. Please click "Show console " on the right panel of the snippet to access the logs

为简单起见,我们将从 body 开始,直到捕获阶段的 span 元素注册处理程序,然后返回到冒泡阶段的 body 元素注册处理程序。所以结果将是一个节点一个节点的事件从开始到结束所采取的方向。请单击代码段右侧面板上的“显示控制台”以访问日志

    function handler(e){
        /* logs messages of each phase of the event flow associated with 
        the actual node where the flow was passing by */

        if ( e.eventPhase == Event.CAPTURING_PHASE ){
            console.log ("capturing phase :\n actual node : "+this.nodeName);
        }
        if ( e.eventPhase == Event.AT_TARGET){
            console.log( "at target phase :\n actual node : "+this.nodeName);
        }
        if ( e.eventPhase == Event.BUBBLING_PHASE){
            console.log ("bubbling phase :\n actual node : "+this.nodeName );
        }
    }

    /* The following array contains the elements between the target (span and you can
    click also on the paragraph) and its ancestors up to the BODY element, it can still
    go up to the "document" then the "window" element, for the sake of simplicity it is 
    chosen to stop here at the body element
    */

    arr=[document.body,document.getElementById("sectionID"),
    document.getElementById("DivId"),document.getElementById("PId"),
        document.getElementById("spanId")];

    /* Then trying to register handelers for both capturing and bubbling phases
    */
        function listener(node){
            node.addEventListener( ev, handler, bool )    
            /* ev :event (click), handler : logging the event associated with 
            the target, bool: capturing/bubbling phase */
        }
        ev="click";
        bool=true; // Capturing phase
        arr.forEach(listener);
        bool=false; // Bubbling phase
        /* Notice that both capturing and bubbling 
        include the at_target phase, that's why you'll get two `at_target` phases in
        the log */
        arr.forEach(listener);
        p {
            background: gray;
            color:white;
            padding: 10px;
            margin: 5px;
            border: thin solid black
        }
        span {
            background: white;
            color: black;
            padding: 2px;
            cursor: default;
        }
    <section ID="sectionID">
            <div  id="DivId">
                <p id="PId">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis <span id="spanId">CLICK ME </span> imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosq.
                </p>
            </div>
    </section>

Notice that events such as focus don't bubble, which makes sens still he majority of events do bubble.

请注意,诸如 focus 之类的事件不会冒泡,这使得大多数事件仍然会冒泡。