HTMLElement自定义事件

时间:2018-02-23 09:11:28

标签: javascript

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

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

以及如何dispatch我的活动?我想致电event.dispatch()cb1cb2cb3应该致电

1 个答案:

答案 0 :(得分:1)

只需使用Event创建new Event('hello');,然后逐个为每个div发送。{/ p>

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>