gpt4 book ai didi

javascript - HTMLElement 自定义事件

转载 作者:行者123 更新时间:2023-12-03 02:25:55 24 4
gpt4 key购买 nike

我创建了一个自定义事件。 var event = new Event('hello');,向节点添加监听器

div1.addEventListener('hello', /*cb1*/);
div2.addEventListener('hello', /*cb2*/);
div3.addEventListener('hello', /*cb3*/);

以及如何调度我的事件?我想调用 event.dispatch() 并调用 cb1cb2cb3

最佳答案

只需使用 new Event('hello'); 创建 Event 并为每个 div 逐个分派(dispatch)它们。

div1.addEventListener('hello', function(){
console.log( "Event called for " + this.id );
});
div2.addEventListener('hello', function(){
console.log( "Event called for " + this.id );
});
div3.addEventListener('hello', function(){
console.log( "Event called for " + this.id );
});

var event = new Event('hello');
div1.dispatchEvent( event );
div2.dispatchEvent( event );
div3.dispatchEvent( event );
<div>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
</div>

关于javascript - HTMLElement 自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48944499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com