Home > Web Front-end > JS Tutorial > Learn more about event bubbling and capturing in JavaScript

Learn more about event bubbling and capturing in JavaScript

青灯夜游
Release: 2022-08-04 21:02:45
forward
2628 people have browsed it

This article will take you through event bubbling and capturing, and let you understand the js event target search method (bubbling and capturing), event proxy, the difference between e.target and e.currentTarget, preventing bubbling and capturing, Cancel the default event, hope it helps everyone!

1. EventTarget event target search method (bubble and capture)

Event target refers to the element to which the event is bound, elemet .addEventListener('click',function(){}) The elemet here is the event target.

Bubbling and capturing:

  • Bubble events:

    • The event defaults to bubbling execution from bottom to top. Taking click events as an example, when we click on a child element, click events on the parent element and above can also be triggered. The order of event execution is from bottom to top, which is the bubbling event.
  • Capture events:

    • Of course, there is also a top-down capture method. Still taking the click event as an example, when a child element is bound to a click event, and we click on the child element, the click events bound to the parent element and above elements will also be executed. The execution order of events is from top to bottom, which is the capture event.

##addEventListener(type,listener,useCapture) Simple analysis:

    type: event Type
  • listener: event listening processing function
  • useCapture: set the event search method
    • false, bubbling event (default value)
    • true, capture event

Parameter useCapture analysis:

Key point! ! The entire process of triggering an event target is divided into two stages (capturing and bubbling). useCapture This value determines at which stage the triggering of the event target is executed.

Sequence analysis of bubbling and capturing:

Learn more about event bubbling and capturing in JavaScript

    It can be seen from the picture It can be seen that the event is captured first and then the event is bubbled. Event capture is from top to bottom (external events are triggered first), and event bubbling is from bottom to top (internal events are triggered first).
  • The process of capturing is from unspecific to specific, and bubbling is from specific to unspecific.
  • Although
  • capture takes precedence, bubbling events are the default method of delivery. This means that events are triggered in the bubbling stage by default.
  • Point! ! The search for event targets is divided into two stages: "bubble" and "capture". The order in which event targets are triggered depends on which stage. If there are both captures and bubbles in the nested elements, the capture must take priority. After the events in the capture phase are executed, the events in the bubbling phase will be executed.

Code demonstration:

    <div>
        这是div1
        <div>
            这是div2
            <div>这是div3</div>
        </div>
    </div>
    <script>
        let div1 = document.getElementById(&#39;div1&#39;);
        let div2 = document.getElementById(&#39;div2&#39;);
        let div3 = document.getElementById(&#39;div3&#39;);
        div1.addEventListener(&#39;click&#39;,function(){
            console.log("这是div1的点击事件");
        },false);
        div2.addEventListener(&#39;click&#39;,function(){
            console.log("这是div2的点击事件");
        },false);
        div3.addEventListener(&#39;click&#39;,function(){
            console.log("这是div3的点击事件");
        },false);
    </script>
Copy after login
When we click on div3, as can be seen from the console results below, the events here are Executed during the bubbling phase.

Learn more about event bubbling and capturing in JavaScript

Still click on div3, we change the third parameter of

div1.addEventListener to true. As shown below, div1 is executed first, indicating the capture stage. Prioritizes the bubbling phase.

Learn more about event bubbling and capturing in JavaScript

Be sure to type after reading this. I have not listed all the situations. I will leave the rest of the situations for you to try and summarize (it is enough to understand the above, Real coding won't be very complicated).

The above is my understanding of the two mechanisms for event target search

Bubbles and Capture.

2. Event proxy mechanism (event delegation)

Use event bubbling to complete the event proxy mechanism:

Copy after login
        
  • 列表1
  •     
  • 列表2
When We need to bind a click event to

li in the above list. Click to obtain the content in li. Generally, we use for to traverse the elements to bind the click event.

let lis = document.querySelectorAll('li');
for (let i = 0; i  If we have 10,000 <p>li<code> nodes, we need to bind 10,000 events using the above method, which greatly affects the code performance. So we can use the bubbling mechanism to solve the above problem, which is to bind the event to the parent element </code>ul<code>. Look at the following code: </code></p><pre class="brush:php;toolbar:false">
    
Copy after login
            
  • 列表1
  •         
  • 列表2
  •     
    <script> let ul = document.querySelector(&#39;ul&#39;); //我们可以通过事件对象(e)中的target属性可以访问到事件源(也就事件的触发元素) ul.addEventListener(&#39;click&#39;,function(e){ console.log(e.target.innerHTML); },false); </script>

Event object (e): Whether it is addEventListener binding event or direct ".event name", the first parameter in the event listening processing function is event Object. The event object contains detailed information about the event. For example, this object contains: Event source, event id, event type, event-bound element, clicked position when the event is triggered, etc. Among them, e.target can access the event source, which is the source of triggering this event.

既然能给父元素绑定事件监听,又能拿到触发的源头。所以我们通过“e.target”+“冒泡机制”就可以减少事件的绑定,能提升不少的性能。

依次点击列表1与列表2:

Learn more about event bubbling and capturing in JavaScript

总结:通过上面代码我们知道了“事件对象”+“冒泡机制”可以实现事件委托。事件委托就是当事件触发时,通过事件冒泡(或事件捕获)把要做的事委托给父元素来处理。

三、e.target与e.currentTarget的区别:

  • e.target 指向的是触发事件监听的对象(事件源)。
  • e.currentTarget 指向添加监听事件的对象(绑定事件的dom元素)。

四、阻止冒泡与捕获

为什么要阻止冒泡或捕获?

点击当前元素时以冒泡的方式传递事件如果上级元素绑定了同样的事件,就会因为冒泡传递导致触发。同样捕获的过程中,也会触发与当前元素绑定的相同事件的上级。只是触发顺序不同。

事件代理一般使用的冒泡,当然阻止冒泡一般不会影响事件代理,因为顺序问题只会影响捕获事件,这也是为什么都使用冒泡实现事件代理机制。

阻止冒泡或捕获的方法

这里我不考虑兼容性问题,我相信不久将来兼容性可以得到解决。

阻止冒泡w3c推介的方法是event.stopPropagation(),顾名思义停止传播,他是事件对象(event)的方法,此方法是阻止目标元素的继续冒泡(或捕获)

event.stopPropagation()阻止冒泡:

    <div>
        这是div1
        <div>
            这是div2
            <div>这是div3</div>
        </div>
    </div>
    <script>
        let div1 = document.getElementById(&#39;div1&#39;);
        let div2 = document.getElementById(&#39;div2&#39;);
        let div3 = document.getElementById(&#39;div3&#39;);
        div1.onclick = function (e) {
           alert(&#39;div1&#39;);
        }
        div2.onclick = function (e) {
           e.stopPropagation();
            alert(&#39;div2&#39;);
        }
        div3.onclick = function (e) {
           alert(&#39;div3&#39;);
        }
    </script>
Copy after login

上面代码默认都是冒泡事件,我们点击div3会依次弹出’div3’与’div2’,为什么没有弹出’div1’这是因为e.stopPropagation();阻止了目标元素的事件继续冒泡到上级。如果每个点击事件都加上了e.topPropagation就不会出现多弹窗的情况。

event.stopPropagation()阻止捕获:

    <div>
        这是div1
        <div>
            这是div2
            <div>这是div3</div>
        </div>
    </div>
    <script>
        let div1 = document.getElementById(&#39;div1&#39;);
        let div2 = document.getElementById(&#39;div2&#39;);
        let div3 = document.getElementById(&#39;div3&#39;);
        div1.addEventListener(&#39;click&#39;,function(e){
           	console.log(&#39;div1&#39;);
        },true);
        div2.addEventListener(&#39;click&#39;,function(e){
            console.log(&#39;div2&#39;);
            e.stopPropagation();
        },true);
        div3.addEventListener(&#39;click&#39;,function(e){
            console.log(&#39;div3&#39;);
        },true);
    </script>
Copy after login

当我们点击div2会依次弹出’div1’与’div2’,这也是因为在div2事件中我们设置了e.stopPropagation(),阻塞了目标元素的事件继续向下捕获。

event.target == event.currentTarget:

div.addEventListener('click',function(e){
	if(event.target == event.currentTarget){
        //需要执行的代码
    }
});
Copy after login

此方法不过多解释用的不多,如果你理解了上面的内容,这个方法也能理解。

五、补充:为什么要使用addEventListener()

从上面代码不难看出addEventListener()有如下的优点(以下是MDN的原话):

addEventListener() 是 W3C DOM 规范中提供的注册事件监听器的方法。它的优点包括:

  • 它允许给一个事件注册多个监听器。 特别是在使用AJAX库,JavaScript模块,或其他需要第三方库/插件的代码。
  • 它提供了一种更精细的手段控制 listener 的触发阶段。(即可以选择捕获或者冒泡)。
  • 它对任何 DOM 元素都是有效的,而不仅仅只对 HTML 元素有效。

六、取消默认事件

event.preventDefault()

默认事件指的是<a href=""></a><input type="submit"> 标签这类有默认行为的标签,通过点击可以跳转或提交。我们给这类标签绑定一个点击事件,设置事件对象的preventDefault()方法就可以阻止默认事件的发生。

   <a>点击跳转</a>
    <script>
        let a = document.querySelector(&#39;a&#39;);
        addEventListener(&#39;click&#39;,function(e){
            e.preventDefault();
        })
    </script>
Copy after login

那么我们如何才能知道一个标签是否有默认事件,打印事件对象的cancelable属性,通过事件执行就可以知道e.cancelable的结果,如果为false表示有默认事件,true则没有。

return false;

事件执行函数中设置return false取消默认事件,但此方法不常用。

【相关推荐:javascript学习教程

The above is the detailed content of Learn more about event bubbling and capturing in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template