0
私はこれが最善のコードで尋ねていると思う:DOM CustomEventリスナー
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);
私が間違って何をしているのですか?これはイベントの仕組みですか? 私の質問は、イベントがリスナーコールバック
element.addEventListener("custom", function(){});
これに追加するには逆に、リスナーをドキュメント本体に適用すると、そのイベントが本体または要素でトリガされるかどうかが発生します。 – relic
@relic - もちろん、イベントリスナーがボディー上にあった場合、ボディーまたはその子のイベントをトリガーすると、イベントハンドラーが起動します。 – adeneo
私はあなたや何かを修正するためにそれを持ち出していませんでしたが、OPの利益のためにそれを指摘しました。 – relic