Analysis of event model in js
This article mainly introduces the event model in JavaScript, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
0. Events and event flow
An event is the moment when the browser interacts with the document, such as clicking a button, filling in a form, etc. It is the bridge of communication between Javascript and HTML. DOM is a tree structure. If events are bound to both parent nodes at the same time, when the child nodes are triggered, the order in which these two events occur will involve the content of the event stream, which describes the order in which the page is accepted. Event flow describes the order in which events are received from the page, but what is more interesting is that the IE and Netscape development teams actually proposed almost completely opposite concepts. IE's event flow is an event bubbling flow, while Netscape Communicator's event flow is an event capture flow.
As a result, event streams are mainly divided into two types: event bubbling and event capture.
IE's event flow is called event bubbling, that is, the event is initially received by the most specific element (the node with the deepest nesting level in the document), and then propagates upwards to less specific nodes (the document) ). Another event stream proposed by the Netscape team is called event capturing. The idea of event capturing is that less specific nodes should receive events earlier, and the most specific nodes should receive events last. The purpose of capture is to capture an event before it reaches its intended destination.
The event flow specified by DOM2-level events includes three stages: event capture stage, target stage, and event bubbling stage. The first thing that happens is event capture, which provides the opportunity to intercept the event. Then the actual target receives the event. The final phase is the bubbling phase, where you can respond to events.
1. DOM0-level event model
The DOM0-level event model is an early event model, also known as the original event model. In this model, events will not propagate , that is, there is no concept of event flow. The event binding listening function is relatively simple. To use Javascript to specify an event handler, you must first obtain a reference to the object to be operated.
Each element (including window and document) has its own event handling attributes. These attributes are usually all lowercase, such as onclick. You can specify an event handler by setting this property to a function:
btn = document.getElementById("myBtn"= "Clicked!"
//HTML事件处理程序<form method="post"> <input type="text" name="username" value=""> <input type="button" value="Username" onclick = "alert(username.value)"> </form>
## 2 . DOM2-level event model
In this model, it is divided into three processes: event capture stage, event bubbling stage in target stage 7;
- Event capturing phase (capturing phase). The event propagates from the document all the way down to the target element, and checks whether the passing nodes are bound to the event listening function, and executes it if so.
- Event processing phase (target phase). When the event reaches the target element, the listening function of the target element is triggered.
- Event bubbling phase. The event bubbles from the target element to the document, and checks whether the passing nodes are bound to the event listening function, and executes it if so.
var btn = document.getElementById("myBtn"); btn.addEventListener("click", functioin() { alert(this.id); }, false); btn.addEventListener("click", function() { alert("Hello Kid"); }, false);
var btn = document.getElementById("myBtn");var handler = function() { alert(this.id); };
"click", handler, btn.removeEventListener("click", handler, );
3. Event model in IE
IE uses two methods similar to those in DOM: attachEvent() and detachEvent(). Both methods accept the same two parameters, event handler name and event handler function. Since IE8 and earlier versions only support event bubbling, event handlers added through attachEvent() will be added to the bubbling phase. If you use attachEvent() to add an event handler to the button, it is available:var btn = document.getElementById("myBtn");var handler = function() { alert(this.id); }; btn.attachEvent("onclick", handler);//添加事件处理程序btn.detachEvent("onclick", handler);//删除事件处理程序
4. Event object
DOM The event object in- type represents the triggered event type
- target represents the target of the event
- currentTarget represents the element where the event handler is currently processing the event
cancelable (Boolean) 表明是否可以取消事件的默认行为
bubbles (Boolean)表明事件是否冒泡
perventDefault()取消事件的默认行为。如果cancelable为true,则可以使用这个方法
stopPropagation()取消事件的进一步捕获或冒泡。如果bubbles为true,则可以使用这个方法。
IE中的事件对象
type表示被触发的事件类型
srcElement表示事件的目标
cancelBubble (Boolean)默认是false,将其设为true就可以取消事件冒泡
returnValue (Boolean) 默认是true,将其设置为false就可以取消事件的默认行为
有了上面的事件对象,就可以写出跨浏览器的事件对象封装成事件包裹了。
var EventUtil = { addHandler: function(element, type, handler){ if (element.addEventListener){ element.addEventListener(type, handler, false); } else if (element.attachEvent){ element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; } }, removeHandler: function(element, type, handler){ if (element.removeEventListener){ //DOM2 element.removeEventListener(type, handler, false); } else if (element.detachEvent){ //IE element.detachEvent("on" + type, handler); } else { element["on" + type] = null; //DOM0 } }, getEvent: function(event){ return event ? event : window.event; }, getTarget: function(event){ return event.target || event.srcElement; }, preventDefault: function(event){ if (event.preventDefault){ event.preventDefault(); } else { event.returnValue = false; } }, stopPropagation: function(event){ if (event.stopPropagation){ event.stopPropagation(); } else { event.cancelBubble = true; } }};
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
通过node.js来调取baidu-aip-SDK实现身份证识别的功能
The above is the detailed content of Analysis of event model in js. 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

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

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











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.
