search
HomeWeb Front-endJS TutorialHow to use JS event binding and event flow model

This time I will show you how to use JS event binding and event flow model. What are the precautions for using JS event binding and event flow model? The following is a practical case. Let’s take a look. .

1. JS events

(1) JS event classification

1. Mouse event :

click/dbclick/mouseover/mouseout

2.HTML event:

onload/onunload/onsubmit/onresize/onchange/onfoucs/onscroll

3. Keyboard events:

keydown: Triggered when the keyboard is pressed

keypress: Triggered the moment the keyboard is pressed and lifted.
keyup: trigger when keyboard is raised

[Notes]

①Execution sequence: keydown keypress keyup

②keypress can only capture numbers, letters, and symbol keys, but not functions key.
③When long pressing, execute keydown--keypress in loop
④If there is keydown, there is not necessarily keyup. When the focus is lost when long pressing, keyup will no longer be triggered
⑤keypress is case-sensitive, keydown, kewup are not different.

4. Event factor:

When an event is triggered, the event will pass in a parameter by default to the function called by the event.

This parameter is a Event factors contain various detailed information of the event.

 document.onkeydown=function(e){
 console.log(e);
 }
document.onkeydown=function(){
console.log(window.event);
}
//兼容浏览器的写法:
document.onkeydown=function(e){
e==e||Window.event;
var Code=e.keyCode||e.which||e.charCode;
if(code==13){
//回车
}
}

5. How to determine the keyboard keys?

①In the re-starting function, receive the event factor e.

② You can use e.key to directly go to the pressed key character (not recommended).
③You can use keyCode/which/charCode to get the ASCII code value of the key.

(Compatible with writing methods of various browsers)

 var Code=e.keyCode||e.which||e.charCode;
//判断组合键
var isAlt=0,isEnt=0;
document.onkeyup=function(e){
if(e.keyCode==18){
isAlt=1;
}      
if(e.keyCode==13){
isEnt=1;
}    
if(isAlt==1&&isEnt==1){
alert("同时按下Alt和Enter键");
}
}
document.onkeyup=function(){
console.log("keyup");
}
document.onkeypress=function(){
console.log("keypress");
}
document.onkeydown=function(){
console.log("keydown");
}
document.onkeypress=function(){
console.log(window.event);
}
//判断是否按下了回车键
document.onkeydown=function(e){
var code=e.keyCode;
if(code==13){
alert("你输入的是回车键");
}
}

2. EventBinding model

(1) DOM0 event model

Notes on binding:

①Use window.onload to bind after loading is complete.

window.onload =function(){//Event}

②Place it behind the body for binding.

//body内容

  <button>内联模型绑定</button>
  <button>哈哈哈哈</button>
  <button>DOM2模型绑定</button>
  <button>取消DOM2</button>
1. Inline model (inline binding): Use the function name directly as the attribute value of the attribute in the html tag.

<button>内联模型绑定</button>
Disadvantages: It does not comply with the basic specifications of the w3c on the separation of content and behavior.

2. Script model (dynamic binding): Select a node in JS and then add the onclick attribute to the node.

document.getElementById("btn1")=function(){}
Advantages: It complies with the basic specifications of the w3c on the separation of content and behavior, and realizes the separation of html and js.

Disadvantages: The same type of event can only be added once to the same node. If added multiple times, the last one will take effect.

document.getElementById("btn1").onclick=function(){
  alert(1234);  
}
document.getElementById("btn1").onclick=function(){
  alert(234);  
}//重复的只能出现最近的一次
3.DOM0 has a common shortcoming: events bound through DOM0 cannot be canceled once bound.

document.getElementById("btn3").onclick=function(){//不能取消匿名函数
  if(btn.detachEvent){
    btn.detachEvent("onclick",func1);
  }else{
    btn.removeEventListener("click",func1);
  }
    alert("取消DOM2");
}
(2) DOM2 event model

1. Add DOM2 event binding:

①Before IE8, use .attachEvent("onclick", function);

②After IE8, use .addEventListener("click", function, true/false);
Parameter three: false (default) means event bubbling, passing in true means event capture.
③ Compatible with all browser processing methods:

 var btn=document.getElementById("btn1");
 if(btn.attachEvent){
 btn.attachEvent("onclick",func1);//事件,事件需要执行的函数IE8可以
 }else{
 btn.attachEventListener("click",func1);
 }
2. Advantages of DOM2 binding:

① The same node can be bound to multiple events of the same type using DOM2.

②Events bound using DOM2 can be canceled with special functions.
3. Cancel event binding:
①Use attachEvent to bind and use detachevent to cancel.
②Use attachEventListener to bind and use removeEventListenter to cancel.
Note: If the event bound to DOM2 needs to be canceled, when binding the event,
the callback function must be a function name, and cannot be an anonymous function, because when the event is canceled, the callback function Enter the function name to cancel.

3. JS event flow model

(1) Event flow model in JS

1. 事件冒泡(fasle/不写):当触发一个节点的事件是,会从当前节点开始,依次触发其祖先节点的同类型事件,直到DOM根节点。
2. 事件捕获(true):当初发一个节点的事件时,会从DOM根节点开始,依次触发其祖先节点的同类型事件,直到当前节点自身。
3. 什么时候事件冒泡?什么时候事件捕获?
 ① 当使用addEventListener绑定事件,第三个参数传为true时表示事件捕获;
 ② 除此之外的所有事件绑定均为事件冒泡。

4. 阻止事件冒泡:

 ① IE10之前,e.cancelBubble = true;
 ② IE10之后,e.stopPropagation();

5. 阻止默认事件:

 ① IE10之前:e.returnValue = false;
 ② IE10之后:e.preventDefault();

//css
#p1{
  width: 300px;;
  height: 300px;
  background-color: powderblue;
}
#p2{
  width: 200px;
  height: 200px;
  background-color: deeppink;
}
#p3{
  width: 100px;
  height: 100px;
  background-color:#A9A9A9;
}
//html
<p>
  </p><p>
    </p><p></p>
  

<a>超链接</a>
p1.addEventListener("click",function(){
  console.log("p1 click");
},false);
p2.addEventListener("click",function(){
  console.log("p2 click");
},false);
p3.addEventListener("click",function(){ //原来的顺序是:3-->2-->1。
//  myParagraphEventHandler(); //截获事件流后,只触发3.但是从2开始依然会冒泡;
  console.log("p3 click");
},false);

结果(事件冒泡)(由小到大p3-》p2-》p1):

p1.addEventListener("click",function(){
  console.log("p1 click");
},true);
p2.addEventListener("click",function(){
  console.log("p2 click");
},true);
p3.addEventListener("click",function(){ 
//  myParagraphEventHandler(); //截获事件流后,只触发3.但是从2开始依然会冒泡;
  console.log("p3 click");
},true);

结果(事件捕获)(由小到大p3-》p2-》p1):

//依然遵循事件冒泡
document.onclick=function(){
  console.log("document click")
}
//截获事件流阻止事件冒泡
function myParagraphEventHandler(e) {
   e = e || window.event;
  if (e.stopPropagation) {
     e.stopPropagation(); //IE10以后 
  } else {
     e.cancelBubble = true; //IE10之前
   }
}
//截获事件流阻止事件冒泡
function myParagraphEventHandler(e) {
   e = e || window.event;
  if (e.stopPropagation) {
     e.stopPropagation(); //IE10以后 
  } else {
     e.cancelBubble = true; //IE10之前
   }
}
//阻止默认事件
function eventHandler(e) {
  e = e || window.event;
// 防止默认行为 
   if (e.preventDefault) {
     e.preventDefault(); //IE10之后
  } else {
     e.returnValue = false; //IE10之前  
  }
}

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

如何操作angular6中使用less

怎样优化js async函数

The above is the detailed content of How to use JS event binding and event flow model. 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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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 Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool