<div class="s">
<div class="parent">
<div class="child"></div>
</div>
</div>
// 创建自定义事件
var evt = new window.CustomEvent('haha', {
bubbles: true, // 是否可冒泡
cancelable: true, //是否可取消
detail: 'msg' // 传递的参数
});
document.querySelector('.s').addEventListener('haha',function(e) {
alert('s' + e.detail);
});
document.querySelector('.child').addEventListener('haha',function(e) {
alert('child' + e.detail);
});
// 触发事件
document.querySelector('.parent').dispatchEvent(evt);
运行:
alert弹出 s msg
若将bubbles设置为false,则什么也不弹
网友评论