Take you to quickly understand the event model in JavaScript
This article mainly introduces the event model in javascript, which includes DOM0-level event model and DOM2-level event model (event capture and event bubbling and DOM2-level registration events and deactivation events) Friends who are familiar with JavaScript can refer to this article
There are two event models in JavaScript: DOM0 and DOM2. As for these two time models, I have never been very clear about them. Now I finally understand a little more by looking up information online.
1. DOM0-level event model
The DOM0-level event model is an early event model and is supported by all browsers. Its implementation is also relatively simple. The code is as follows:
<p id = 'click'>click me</p> <script> document.getElementById('click').onclick = function(event){ alert(event.target); } </script>
This event model is to register the event name directly on the dom object. This code registers an onclick event on the p tag and outputs it inside the event function. Click target. Dismissing the event is even simpler, just copy null to the event function, as follows:
document.getElementById('click'_).onclick = null;
From this we can We know that in dom0, a dom object can only register one function of the same type, because if multiple functions of the same type are registered, overwriting will occur and the previously registered functions will be invalid.
var click = document.getElementById('click'); click.onclick = function(){ alert('you click the first function'); }; click.onclick = function(){ alert('you click the second function') }
In this code, we registered two onclick functions for the DOM object, but as a result, only the second registered function was executed, and the previously registered function was overwritten.
2. DOM2-level event model
1. Event capture and event bubbling (capture, bubble)
First of all, IE8 and below do not support this event model. The mechanism of event capture and event bubbling is as follows:
As shown in the figure above, 123 represents event capture and 4567 represents event bubbling. First we use the following code:
<p id = 'outer' style = 'margin: 100px 0 0 100px; width: 200px;height: 200px; background: red;'> <p id="inner" style = 'margin-left:20px; width: 50px;height:50px; background: green;'></p> </p>
Suppose we click on p with the ID inner, then the event flow at this time is to first execute the capture phase: document-html-body-p(outer) . Then execute the bubbling phase: p(inner)-p(outer)-body-html-document.
2. DOM2-level registration events and deactivation events
Use addEventListener and removeEventListener in DOM2 level to register and deactivate events (IE8 and Not supported in previous versions). The advantage of this function compared to the previous method is that a DOM object can register multiple events of the same type, and event overwriting will not occur, and each event function will be executed in sequence.
addEventListener('event name','event callback','capture/bubble'). The example is as follows:
<p id = 'outer' style = 'margin: 100px 0 0 100px; width: 200px;height: 200px; background: red;'> <p id="inner" style = 'margin-left:20px; width: 50px;height:50px; background: green;'></p> </p> <script> var click = document.getElementById('inner'); click.addEventListener('click',function(){ alert('click one'); },false); click.addEventListener('click',function(){ alert('click two'); },false); </script>
First we need to know that the first parameter of addEventListenr is the event name. Different from DOM level 0, there is no "on". In addition, the third parameter represents capture or bubbling, and true represents the capture event. , false represents a bubbling event.
In this code, we registered two click event functions for inner p. The result is that the browser will execute these two functions in sequence.
Next we demonstrate how to use the event stream generation mechanism.
<p id = 'outer' style = 'margin: 100px 0 0 100px; width: 200px;height: 200px; background: red;'> <p id="inner" style = 'margin-left:20px; width: 50px;height:50px; background: green;'></p> </p> <script> var click = document.getElementById('inner'); var clickouter = document.getElementById('outer'); click.addEventListener('click',function(){ alert('inner show'); },true); clickouter.addEventListener('click',function(){ alert('outer show'); },true); </script>
In this code, we use the capture event. Since inner is nested in outer, we know that when using capture, outer should capture the event first, and then inner can capture it. this incident. Then the result is that outer is executed first, followed by inner.
So what if I change the execution timing of outer to the bubbling stage?
alickouter.addEventListener('click',function(){ alert('outer show'); },false);
In this case, inner is executed first and then outer. In the same way, if we change the execution timing of both events to the bubbling stage, the inner will still be executed first and then the outer. Then there is another problem, that is, if we register two click events in inner, one is in the capturing phase and the other is in the bubbling phase, that is to say, the third parameter of addEventListenter is set to false and true respectively, then execute What is the order of .
<script> var click = document.getElementById('inner'); var clickouter = document.getElementById('outer'); click.addEventListener('click',function(){ alert('capture show'); },true); click.addEventListener('click',function(){ alert('bubble show'); },false); </script>
In this case, the first thing to do is the capture show, followed by the bubble show. However, this result is related to the order of registration. The first to register will be executed first. Because we are looking at the diagram of event capture and event bubbling, we find that there is only one specific DOM object in the end.
So what if we register click events for both outer and inner but I don’t want outer to execute? At this time, we need to use the stopPropagation function. This function is used to prevent bubbling. The implication is that the event will no longer continue to bubble, so that the DOM object that registers the same type of event will not be executed.
For example, when making a homemade drop-down box, we click elsewhere in the browser and we need the options of the drop-down box to be hidden. In this case, we need to use stopPropagation. as follows:
<script> var click = document.getElementById('inner'); var clickouter = document.getElementById('outer'); click.addEventListener('click',function(event){ alert('inner show'); event.stopPropagation(); },false); clickouter.addEventListener('click',function(){ alert('outer show'); },false); </script>
正常的情况下,我们在不添加stopPropagation函数时,首先应该执行inner,然后执行outer,但是当我们在inner的事件函数中添加了stopPropagation函数之后,执行完inner的事件函数之后,就不会在执行outer的事件函数了,也可以理解为事件冒泡到inner之后就消失了,因此也就不会在执行接下来的事件函数了。
由于事件捕获阶段没有可以阻止事件的函数,所以一般都是设置为事件冒泡。
相关推荐:
The above is the detailed content of Take you to quickly understand the event model in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

jQuery is a popular JavaScript library that can be used to simplify DOM manipulation, event handling, animation effects, etc. In web development, we often encounter situations where we need to change event binding on select elements. This article will introduce how to use jQuery to bind select element change events, and provide specific code examples. First, we need to create a dropdown menu with options using labels:

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Methods for building event-based applications in PHP include using the EventSourceAPI to create an event source and using the EventSource object to listen for events on the client side. Send events using Server Sent Events (SSE) and listen for events on the client side using an XMLHttpRequest object. A practical example is to use EventSource to update inventory counts in real time in an e-commerce website. This is achieved on the server side by randomly changing the inventory and sending updates, and the client listens for inventory updates through EventSource and displays them in real time.

In-depth understanding of the close button event in jQuery During the front-end development process, we often encounter situations where we need to implement the close button function, such as closing pop-up windows, closing prompt boxes, etc. When using jQuery, a popular JavaScript library, it becomes extremely simple and convenient to implement the close button event. This article will delve into how to use jQuery to implement close button events, and provide specific code examples to help readers better understand and master this technology. First, we need to understand how to define
