search
HomeWeb Front-endJS TutorialDetailed introduction to several types of event handlers in js

An event is a certain action performed by the user or the browser itself, such as click, laod, and mouseover are the names of events.

#Event flow describes the order in which events are received from the page.

#Event handlers are functions that respond to events. The name of the event handler starts with "on". For example, the name of the event handler corresponding to the click event is onclick.

There are many ways to specify handlers for events, such as: HTML event handler, DMO level 0 event handler, DOM level 2 event handler, IE event Handlers, cross-browser event handlers.

(1)html event handler

That is: write the event handler in the corresponding html tag.

eg:

<input type="button" value="click me" onclick="alert("hello")" />

Disadvantages: ①There is a time difference. When the user triggers the corresponding event as soon as the html element appears on the page, the event handler may not yet have the execution conditions. (For example, if the called function has not been parsed yet), an error will occur. eg:

<input type="button" value="click me" onclick="message()" />
<script type="text/javascript">function message(){alert("hello world");}</script>

Because the called function is below the button, if the button is clicked before the message function is loaded, an error will occur.

②The coupling between html and js code is too high. If you want to change the event handler, you need to change two places: html code and javascript code.

(2) DMO level 0 event handler

eg:
var btn=document.getElementById("myBtn");
  btn.onclick=function(){alert(this.id)};

Note: If this code is located after the button, there may be no response no matter how you click it for a while, because in this code The event handler will not be specified before running.

The DMO level 0 event handler is considered a method of the element. In other words, the DMO level 0 event handler runs in the scope of the element, so this in the program refers to the current element. Any properties and methods of the element can be accessed through this in the event handler.

Event handlers added in this way will be processed during the bubbling phase of the event flow.

You can also delete the specified event handler. Just set the attribute of the event handler to null.

eg:
btn.onclick=null;将处理程序设置为null以后,再点击按钮不会发生任何动作。

(3) DOM2-level event handler

DOM2-level event defines two methods for specifying and deleting event handlers. These two operations are: addEventListener() and removeEventListner(). All DOM nodes contain these two methods. They need to accept 3 parameters: the event name to be processed, the processing function, and the Boolean value. If the last Boolean parameter is true, it means that the handler is called in the capture phase. If it is false, it means that the event handler is called in the bubbling phase.

For example, to add an event handler for click on a button, you can use the following code:

var btn=document.getElementById("myBtn");
btn.addEventListner("onclick",function(){alert("hello world");false});这里添加的事件处理程序也是依附于元素的的作用域

The advantage of using DOM2 event handlers is that you can add multiple event handlers for the same element. .

例:var btn=getElementById("myBtn");
btn.addEventListner("click",function(){alert(this.id);},flase);
btn.addEventListner("click",function(){alert("hello world");},flase);

Result: The id is displayed first, then hello world.

Event handlers added through addEventListner() can only be removed through removeEventListner. The parameters used for removal are the same as for adding an event handler. Another note: Anonymous functions added through addEventListner cannot be deleted.

(4) IE event handler.

The functions of IE to add and delete event handlers are: attachEvent() and detachEvent(); these two functions receive the same two parameters: event handler name and event handling function. Since IE only supports event bubbling, event handlers added through attachEvent will be added to the bubbling stage.

例如:var btn=document.getElementById("myBtn");
btn.attachEvent("onclick",function(){alert("hello world");});

IE When using the attachEvent method, the scope of the event handler is the global scope, so this is equal to window. (This is very important to remember when writing cross-browser code).

Similar to addEventListner, the attachEvent() method can also be used to add multiple event handlers to an element;

eg:
var btn=document.getElementById("myBtn");
btn.attachEvent("onclick",function(){alert("clicked");});
btn.attachEvent("onclick",function(){alert("hello world");});

It is worth noting that the handlers for these events are triggered in reverse order. , that is, pop up hello world first and then pop up clicked.

The usage of detach() is omitted.

(5) Cross-browser event handler

In order to handle events in a cross-browser manner, there are two main methods you can use:

①Use to isolate browsing js library that implements differences.

②Write the most suitable event processing method yourself. Capability detection is used here, that is: identifying the browser's capabilities. To ensure that the code runs consistently under most browsers, just focus on the bubbling phase.

The code steps are as follows: The first method to be created is addHandler (used to deal with cross-browser compatibility issues, no specific code is given here). Its responsibility is to determine whether to use DOM0 level method or DOM2 depending on the situation. Level method, IE method to add events. addHandler receives 3 parameters: the element to be operated on, the event name, and the event handler function. This method belongs to an object named EventUtil. This object is used here to handle differences between browsers.

The method corresponding to addHandler is removeHandler(), which also accepts the same parameters. The responsibility of this event is to remove the previously added event handler. No matter how the event is added to the object, if other methods are invalid, the DOM level 0 method will be used by default.

使用EventUtil的方法如下:var btn=document.getElementById("myBtn");
var hander=function(){alert("hello")};//事件处理程序
EventUtil.addHandler(btn,"onclick",handler);
//其他代码
EventUtil.removeHandler(btn,"onclick",handler);
addHandler()和removeHandler()没有考虑到所有的浏览器问题,例如IE中作用域的问题,但是使用它们添加和移除事件处理程序还是足够了。

上面是我整理给大家的在js中详细介绍几种类型的事件处理程序的方式,希望今后会对大家有帮助。

相关文章:

重点解答动态加载JS脚本,一语道破

javascript中遍历EL表达式List集合中的值

如何在<script></script>标签中一样可以使用el表达式

The above is the detailed content of Detailed introduction to several types of event handlers in js. 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 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.

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

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 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool