为什么用dispatchEvent触发已定义的事件不遵循事件的冒泡行为? [英] Why firing a defined event with dispatchEvent doesn't obey the bubbling behavior of events?
问题描述
我对以下脚本感到困惑:
I'm confused with the script below:
var event = new Event('shazam');
document.body.addEventListener('shazam',function(){
alert('body');
});
document.addEventListener('shazam',function(){
alert('document');
});
window.addEventListener('shazam',function(){
alert('window');
});
document.body.dispatchEvent(event);
当我在浏览器中运行此脚本时,我仅收到 alert('body'); 事件. 但是,如果我将addEventListener的捕获参数(第三个可选参数)设置为true,则会按顺序捕获所有警报.
When I run this script on my browser, I just get the alert('body'); event. but if i set the capturing parameter of addEventListener (the third optional parameter) to true, all the alerts captured in order they should.
为什么 shazam事件 没有出现?
Why the shazam event doesn't bubble up ?
推荐答案
您需要将bubbles
属性设置为true,并且必须在构造过程中执行以下操作:
You need to set the bubbles
property to true, and you have to do this during the construction:
var event = new Event('shazam', { bubbles: true });
或使用initEvent
的旧方法,将true作为第二个参数传递以允许冒泡:
or the old way with initEvent
, passing true as the second argument to allow bubble:
event.initEvent('shazam', true);
这篇关于为什么用dispatchEvent触发已定义的事件不遵循事件的冒泡行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!