Javascript DOM自定义事件侦听器

Javascript DOM自定义事件侦听器,javascript,html,events,dom,custom-events,Javascript,Html,Events,Dom,Custom Events,我认为最好用代码来问这个问题: 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) {

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

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(){});

您必须将事件分派到实际正在侦听它的元素上,或者分派到链中较低的一个元素(如果假定它冒泡的话)

您不能在DIV上侦听事件,然后在BODY标记上分派事件,并期望它向下冒泡

element.dispatchEvent(event);

是触发事件的正确方法,它不会从主体冒泡到子对象,事件只会向上冒泡到DOM链。

若要添加此项。。。相反,您可以将侦听器应用于文档正文,无论事件是在正文上触发还是在元素上触发,它都会触发。@relic-当然,如果事件侦听器在正文上,则触发正文上的事件或其任何子项,都会触发事件处理程序。对。我提出来不是为了纠正你或其他什么,只是为了行动的利益指出它。这是有道理的。谢谢