【问题标题】:DOM CustomEvent listenersDOM 自定义事件监听器
【发布时间】:2016-07-01 21:09:42
【问题描述】:

我认为最好用代码来问这个问题:

var event = new CustomEvent("custom", {bubbles: true}); // Create Event

// Create and attach element
var element = document.createElement("div");
document.body.appendChild(element);

element.addEventListener("custom", function(e) {
    console.log("listening");
});

// At this point I thought that if the "custom" event were fired that my  
// element listing would be triggered with the listener callback.
// But.... 

document.body.dispatchEvent(event);
// check the console... nothing :(

// the only way I am able to get my element event listener to fire is if 
// the element calling the dispatchEvent(event) is the element itself.
element.dispatchEvent(event);

我做错了什么?这是事件的工作方式吗? 我的问题是如何在未调度事件时收听自定义事件

dispatchEvent(event)

来自包含侦听器回调的元素

element.addEventListener("custom", function(){});

【问题讨论】:

    标签: javascript html events dom custom-events


    【解决方案1】:

    您必须在实际监听它的元素上调度事件,或者如果它应该冒泡,则在链中较低的元素上调度。

    你不能在 DIV 上监听事件,然后在 BODY 标签上调度事件,并期望它向下冒泡

    element.dispatchEvent(event);
    

    是触发事件的正确方法,它不会从 body 冒泡到 child,事件只会在 DOM 链中向上冒泡。

    【讨论】:

    • 添加到这个...相反,您可以将您的侦听器应用到文档正文,无论是在正文还是元素上触发事件,它都会触发。
    • @relic - 当然,如果事件监听器在 body 上,触发 body 上的事件,或者它的任何子事件,都会触发事件处理程序。
    • 对。我不是为了纠正你或任何事情而提出它,只是为了 OP 的利益而指出它。
    • 这是有道理的。谢谢。
    最近更新 更多