Table of Contents
1. EventTarget event target search method (bubble and capture)
三、e.target与e.currentTarget的区别:
四、阻止冒泡与捕获
六、取消默认事件
Home Web Front-end JS Tutorial Learn more about event bubbling and capturing in JavaScript

Learn more about event bubbling and capturing in JavaScript

Aug 04, 2022 pm 09:01 PM
javascript Event bubbling capture events event agent

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Understand the event bubbling mechanism: Why does a click on a child element affect the event of the parent element? Understand the event bubbling mechanism: Why does a click on a child element affect the event of the parent element? Jan 13, 2024 pm 02:55 PM

Understanding event bubbling: Why does a click on a child element trigger an event on the parent element? Event bubbling means that in a nested element structure, when a child element triggers an event, the event will be passed to the parent element layer by layer like bubbling, until the outermost parent element. This mechanism allows events on child elements to be propagated throughout the element tree and trigger all related elements in turn. To better understand event bubbling, let's look at a specific example code. HTML code: <divid="parent&q

Reasons and solutions for jQuery .val() failure Reasons and solutions for jQuery .val() failure Feb 20, 2024 am 09:06 AM

Title: Reasons and solutions for the failure of jQuery.val() In front-end development, jQuery is often used to operate DOM elements. The .val() method is widely used to obtain and set the value of form elements. However, sometimes we encounter situations where the .val() method fails, resulting in the inability to correctly obtain or set the value of the form element. This article will explore the causes of .val() failure, provide corresponding solutions, and attach specific code examples. 1.Cause analysis.val() method

Why does event bubbling trigger twice? Why does event bubbling trigger twice? Feb 22, 2024 am 09:06 AM

Why does event bubbling trigger twice? Event bubbling (Event Bubbling) means that in the DOM, when an element triggers an event (such as a click event), the event will bubble up from the element to the parent element until it bubbles to the top-level document object. . Event bubbling is part of the DOM event model, which allows developers to bind event listeners to parent elements, so that when child elements trigger events, the events can be captured and processed through the bubbling mechanism. However, sometimes developers encounter events that bubble up and trigger twice.

Why can't click events in js be executed repeatedly? Why can't click events in js be executed repeatedly? May 07, 2024 pm 06:36 PM

Click events in JavaScript cannot be executed repeatedly because of the event bubbling mechanism. To solve this problem, you can take the following measures: Use event capture: Specify an event listener to fire before the event bubbles up. Handing over events: Use event.stopPropagation() to stop event bubbling. Use a timer: trigger the event listener again after some time.

Why does the event bubbling mechanism trigger twice? Why does the event bubbling mechanism trigger twice? Feb 25, 2024 am 09:24 AM

Why does event bubbling happen twice in a row? Event bubbling is an important concept in web development. It means that when an event is triggered in a nested HTML element, the event will bubble up from the innermost element to the outermost element. This process can sometimes cause confusion. One common problem is that event bubbling occurs twice in a row. In order to better understand why event bubbling occurs twice in a row, let's first look at a code example:

Which JS events don't bubble up? Which JS events don't bubble up? Feb 19, 2024 pm 09:56 PM

What are the situations in JS events that will not bubble up? Event bubbling (Event Bubbling) means that after an event is triggered on an element, the event will be transmitted upward along the DOM tree starting from the innermost element to the outermost element. This method of transmission is called event bubbling. However, not all events can bubble up. There are some special cases where events will not bubble up. This article will introduce the situations in JavaScript where events will not bubble up. 1. Use stopPropagati

What scenarios can event modifiers in vue be used for? What scenarios can event modifiers in vue be used for? May 09, 2024 pm 02:33 PM

Vue.js event modifiers are used to add specific behaviors, including: preventing default behavior (.prevent) stopping event bubbling (.stop) one-time event (.once) capturing event (.capture) passive event listening (.passive) Adaptive modifier (.self)Key modifier (.key)

What are the common ways to prevent bubbling events? What are the common ways to prevent bubbling events? Feb 19, 2024 pm 10:25 PM

What are the commonly used commands to prevent bubbling events? In web development, we often encounter situations where we need to handle event bubbling. When an event is triggered on an element, such as a click event, its parent element will also trigger the same event. This behavior of event delivery is called event bubbling. Sometimes, we want to prevent an event from bubbling up, so that the event only fires on the current element, and prevents it from being passed to superior elements. To achieve this, we can use some common directives that prevent bubbling events. event.stopPropa

See all articles