Why can't events bubble up in some cases?
Event bubbling means that when an event on an element is triggered, the event will be passed upwards starting from the innermost element until it is passed to the outermost element. But in some cases, the event cannot bubble, that is, the event will only be processed on the triggered element and will not be passed to other elements. This article will introduce some common situations, discuss why events fail to bubble, and provide specific code examples.
document.addEventListener('click', function(event) { console.log('捕获阶段'); }, true); document.addEventListener('click', function(event) { console.log('冒泡阶段'); }, false);
In the above code, when you click anywhere on the page, the event will be processed in both the capture phase and the bubbling phase. If the third parameter is set to true, the event will only be processed in the capture phase and will not be bubbled, causing the event to fail to bubble.
document.getElementById('inner').addEventListener('click', function(event) { console.log('内层元素点击事件'); event.stopPropagation(); }); document.getElementById('outer').addEventListener('click', function(event) { console.log('外层元素点击事件'); });
In the above code, when the inner element is clicked, the event is handled on the element but is not passed to the outer element, As a result, events cannot bubble up.
document.addEventListener('contextmenu', function(event) { console.log('右键点击事件'); }); document.addEventListener('click', function(event) { console.log('点击事件'); });
In the above code, when the page is right-clicked, only the right-click event will be triggered, and the click event will not be triggered.
Summary:
The situations where events cannot bubble include using event capture mode, calling stopPropagation method and right mouse click event. Understanding these situations can help us better understand the event delivery mechanism during development and avoid unexpected problems. I hope the above content can inspire readers!
The above is the detailed content of Why do events fail to bubble up?. For more information, please follow other related articles on the PHP Chinese website!