search
HomeWeb Front-endJS TutorialDetailed analysis of js native event description (code attached, simple and clear)

The following are the js native events I have compiled for you. Interested students can take a look.

1. Event flow
Event flow is mainly divided into two types: event bubbling and event capture. Events bubble up, and the target element receives the event first, and then gradually propagates upward to less specific nodes. Event capture is exactly the opposite, the main idea is that less specific nodes receive the event first and then gradually propagate down to the target node.

<html>
    <head>
        <title>事件流</title>
    </head>
    <body>
        <div id ="testDiv"></div>
    </body>
 </html>

When a div is clicked, the bubbling event receives the node order div->body->html->document
The capture event receives the node order document->html->body ->div

2. Event handler
a) HTML event handler
Each event supported by an element can be handled using an HTML attribute with the same name as the corresponding event handler. specified.
Disadvantages: 1. Time difference problem, the user may have clicked on the page element before the browser has parsed the click event function - wrap the error through try-catch
2. The scope chain of the event handler is different Browsers may produce different results.
3. HTML code and Javascript code are tightly coupled, which is not conducive to expansion and maintenance.
b) DOM0 level event handler
Assign the function to the element event handler attribute
var btn = document.getElementById(“#dv”);
btn.onclick = function(){} ;
The event handler of the element that you want to delete – btn.onclicn = null;

The event handler added in this way is processed in the event bubbling phase.

c)DOM2 level event handler
Specify event handler addEventListener
Remove event handler removeEventListener
Receive three parameters, namely the event name to be processed, the function of the event handler, Boolean Value (true means calling the handler in the capture phase, false means calling the event handler in the bubbling phase)

Note: addEventListener must be deleted through removeEventListener and the parameters must be consistent, so the anonymous function added through addEventListener cannot be removed.

d)IE事件处理程序

attachEvent 
detachEvent 
两个方法接收相同的两个参数(”onclick”,”function(){}”); 
由于IE8级更早版本只支持事件冒泡,所以通过attachEvent添加的事件处理程序只能被添加到冒泡阶段。 
注意:attach中第一个参数是onclick而不是addEventListener中的click 
IE事件处理程序attachEvent添加的在全局作用域中运行 

var btn = document.getElementById(“#tes”); 
btn.attachEvent(“onclick”,function(){ 
alert(this == window); //true 
})

3、跨浏览器的事件处理程序。 
由于不同浏览器之间事件处理程序不同,所以有必要编写可以跨浏览器使用的事件处理程序。

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){
            element.removeEventListener(type,handler,false);
        }else if(element.deatchEvent){
            element.deatch("on" + type,handler);
        }else{
            element["on" + type] = null;
        }
    }
}

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

相关文章:

JS弹出窗口代码大全

几个前端常见的JS排序代码

JS去掉字符串前后空格或去掉所有空格的用法

The above is the detailed content of Detailed analysis of js native event description (code attached, simple and clear). 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
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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.