Javascript 事件,捕获作品冒泡不会

标签 javascript events

我对 JS 事件传播的理解是,事件首先“捕获”DOM 树,然后“冒泡”备份,沿途触发处理程序。

<html>
<body>
    <div id="textbox">
        nothing yet
    </div>
</body>

<script>
    // Gets incremented by "update" event
    var val = 0;

    // Event starts here
    textbox = document.getElementById("textbox");
    textbox.addEventListener("update", function(e) {
        textbox.innerHTML = val;
    }, false);

    // Should bubble here
    body = document.getElementsByTagName("body")[0];
    body.addEventListener("update", function(e) {
        val++;
    }, false); 

    function update() {
        var e = new Event("update");

        textbox.dispatchEvent(e);
    }

    setInterval(update, 10);
</script>
</html>

在我的code here正文内有一个 div“文本框”。我认为发送到文本框的更新事件应该冒泡到正文,但事实并非如此。计数器永远不会更新。

如果我将正文事件监听器的 UseCapture 参数设置为 true,计数器会更新。

为什么捕获有效,但不冒泡?

最佳答案

dispatchEvent dispatches你的事件。 Summarizing , 这意味着

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.

因此,如果 bubbles 属性不为真,则事件不会冒泡。

当您使用 Event 创建事件时,您可以将 bubbles 属性设置为 true:

<i>event</i> = new <a href="http://www.w3.org/TR/dom/#concept-event-constructor" rel="noreferrer noopener nofollow">Event</a>(<i>type</i> [, <i>eventInitDict</i>])

Returns a new event whose type attribute value is set to type. The optional eventInitDict argument allows for setting the bubbles and cancelable attributes via object members of the same name.

关于Javascript 事件,捕获作品冒泡不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31818984/

相关文章:

javascript - AngularJS ng-repeat 通过不选择初始值来跟踪

javascript - 如何在不更改循环结构的情况下将字符串添加到 for 循环中的字符串变量?

C#:收集 WeakReference 之前的通知?

javascript - 绑定(bind)事件到文本节点

javascript - 为什么必须将事件对象作为参数传递?

powershell - 如何使用 System.RuntimeCaching.MemoryCache 正确实现 PowerShell 回调

javascript - angular.js - 解析 html 函数需要 2000 毫秒甚至更多

javascript - Angular 6 应用程序在本地主机上加载时卡住

javascript - 如何使用 .addClass 设置下拉列表项

javascript - 异步处理所有事件处理程序的方法?