DOM CustomEvent侦听器

时间:2016-07-01 21:09:43

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

1 个答案:

答案 0 :(得分:0)

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

您无法在DIV上侦听该事件,然后在BODY标记上发送该事件,并期望它向下冒泡

element.dispatchEvent(event);

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