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
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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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 Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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