search
HomeWeb Front-endJS TutorialJavaScript event model (graphic tutorial)

JavaScript event model (graphic tutorial)

May 19, 2018 am 10:09 AM
javascriptjsevent

This article mainly introduces the event model in JavaScript, which includes the DOM0-level event model and the DOM2-level event model (event capture and event bubbling and DOM2-level registration events and deactivation events). Friends who need it can refer to it. 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 = &#39;click&#39;>click me</p>
<script>
 document.getElementById(&#39;click&#39;).onclick = function(event){
  alert(event.target);
 }
</script>


This event model is to register the event name directly on the dom object. This code is on the p tag. An onclick event is registered, and the clicked target is output inside this event function. 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(&#39;click&#39;);
click.onclick = function(){
 alert(&#39;you click the first function&#39;);
};
click.onclick = function(){
 alert(&#39;you click the second function&#39;)
}


In this code, we registered two onclick functions for the dom object, but the result was that only the second one was executed. A registered function, the previously registered function is 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 = &#39;outer&#39; style = &#39;margin: 100px 0 0 100px; width: 200px;height: 200px; background: red;&#39;>
 <p id="inner" style = &#39;margin-left:20px; width: 50px;height:50px; background: green;&#39;></p>
</p>


## Suppose we click on p with the ID of inner, then the event at this time The process 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 = &#39;outer&#39; style = &#39;margin: 100px 0 0 100px; width: 200px;height: 200px; background: red;&#39;>
 <p id="inner" style = &#39;margin-left:20px; width: 50px;height:50px; background: green;&#39;></p>
</p>
<script>
 var click = document.getElementById(&#39;inner&#39;);
 click.addEventListener(&#39;click&#39;,function(){
  alert(&#39;click one&#39;);
 },false);
 click.addEventListener(&#39;click&#39;,function(){
  alert(&#39;click two&#39;);
 },false);
</script>


First we need to know that the first parameter of addEventListenr is the event name, which is different from DOM level 0." on", and the third parameter represents capture or bubbling, true represents the capture event, and false represents the 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 = &#39;outer&#39; style = &#39;margin: 100px 0 0 100px; width: 200px;height: 200px; background: red;&#39;>
 <p id="inner" style = &#39;margin-left:20px; width: 50px;height:50px; background: green;&#39;></p>
</p>
<script>
 var click = document.getElementById(&#39;inner&#39;);
 var clickouter = document.getElementById(&#39;outer&#39;);
 click.addEventListener(&#39;click&#39;,function(){
  alert(&#39;inner show&#39;);
 },true);
 clickouter.addEventListener(&#39;click&#39;,function(){
  alert(&#39;outer show&#39;);
 },true);
</script>


In this code, we use capture events. Since inner is nested in outer, we know when to use When capturing, the outer should capture the event first, and then the inner can capture the event. 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(&#39;click&#39;,function(){
 alert(&#39;outer show&#39;); 
},false);


In this case, the inner is executed first and then the 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(&#39;inner&#39;);
 var clickouter = document.getElementById(&#39;outer&#39;);
 click.addEventListener(&#39;click&#39;,function(){
  alert(&#39;capture show&#39;);
 },true);
 click.addEventListener(&#39;click&#39;,function(){
  alert(&#39;bubble show&#39;);
 },false);
</script>


In this case, the first 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.

比如在自制下拉框的时候,我们点击浏览器的其他位置,我们需要下拉框的options隐藏,这时我们就要用到stopPropagation了。如下:


<script>
 var click = document.getElementById(&#39;inner&#39;);
 var clickouter = document.getElementById(&#39;outer&#39;);
 click.addEventListener(&#39;click&#39;,function(event){
  alert(&#39;inner show&#39;);
  event.stopPropagation();
 },false);
 clickouter.addEventListener(&#39;click&#39;,function(){
  alert(&#39;outer show&#39;);
 },false);
</script>


  正常的情况下,我们在不添加stopPropagation函数时,首先应该执行inner,然后执行outer,但是当我们在inner的事件函数中添加了stopPropagation函数之后,执行完inner的事件函数之后,就不会在执行outer的事件函数了,也可以理解为事件冒泡到inner之后就消失了,因此也就不会在执行接下来的事件函数了。

  由于事件捕获阶段没有可以阻止事件的函数,所以一般都是设置为事件冒泡。

好了以上就是全部内容啦 ,希望对大家的学习有所帮助~~


上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

Vue.js使用开源框架mpvue

p5.js如何进行图片加载

js如何下载图片到本地


The above is the detailed content of JavaScript event model (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools