【发布时间】: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