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


90

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

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

Answers:


11

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

useCapture
如果为true,则useCapture表示用户希望启动捕获。启动捕获后,所有指定类型的事件都将分派给已注册的,listener然后再分派给EventTargetDOM树中位于其下方的任何s。在树中冒泡的事件不会触发指定使用捕获的侦听器。有关 详细说明,请参见DOM 3级事件


25
我对javascript的了解不多,所以我很难得到这个答案。我实际上不知道什么是useCapture?你能告诉我一些有关它的事吗?
2014年

1
@BikashChandraMondal请查看下面的答案。
天秤座

34
请说明,不要只是复制/粘贴。
Damjan Pavlica

3
多么无用的复制粘贴。
塞巴斯蒂安·帕尔马

323

我也检查了MDN,但仍然不明白 useCapture用途,因此此答案适用于那些在检查了官方文档后仍然不了解它的人。

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

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

事件首先下降-称为捕获,然后上升。W3C规范中对此行为进行了规范化处理。

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

这张照片显示了它是如何工作的。

在此处输入图片说明

根据此模型,事件:

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

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

然后是你的问题。调用的第三个参数useCapture指示您希望处理程序在两个阶段中的哪个阶段上处理事件。

useCapture = true

处理程序设置在捕获阶段。在到达孩子之前,将有很多事情发生。

useCapture = false

处理程序设置在冒泡阶段。到达孩子之后,事件就会发生。

这意味着如果您编写如下代码:

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

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

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

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


13
非常好的综合答案。我比现在更了解它。
0x499602D2 2014年

15
很好的解释。人的触动,才是与众不同的。
拉斐尔·伊恩

1
我非常感谢这个解释。
neilsimp1 '16

1
好答案。您还可以解释何时应使用哪种方法吗?
Rahul Arora

1
这必须是选定的答案。OP,你能这样做吗?
萨拉·蒂瓦里

6

@Libra的答案非常好,碰巧有一些像我这样的人,他们更了解代码与机器之间的交互。
因此,以下脚本应解释事件传播。我要根据此描述架构尝试做的是:
跟随事件流在以下层次结构中上下移动:

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

为了简单起见,我们将从主体开始,直到捕获阶段的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>

请注意,诸如焦点之类的事件不会冒泡,这使大多数事件仍然感觉冒泡。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.