Home Web Front-end JS Tutorial Detailed introduction to several types of event handlers in js

Detailed introduction to several types of event handlers in js

May 17, 2018 am 11:05 AM
javascript event type

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")" />
Copy after login

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()" />
Copy after login
<script type="text/javascript">function message(){alert("hello world");}</script>
Copy after login

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)};
Copy after login

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以后,再点击按钮不会发生任何动作。
Copy after login

(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});这里添加的事件处理程序也是依附于元素的的作用域
Copy after login

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);
Copy after login

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");});
Copy after login

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");});
Copy after login

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中作用域的问题,但是使用它们添加和移除事件处理程序还是足够了。
Copy after login

上面是我整理给大家的在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 of this Website
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

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create a video matrix account? What types of matrix accounts do it have? How to create a video matrix account? What types of matrix accounts do it have? Mar 21, 2024 pm 04:57 PM

With the popularity of short video platforms, video matrix account marketing has become an emerging marketing method. By creating and managing multiple accounts on different platforms, businesses and individuals can achieve goals such as brand promotion, fan growth, and product sales. This article will discuss how to effectively use video matrix accounts and introduce different types of video matrix accounts. 1. How to create a video matrix account? To make a good video matrix account, you need to follow the following steps: First, you must clarify what the goal of your video matrix account is, whether it is for brand communication, fan growth or product sales. Having clear goals helps develop strategies accordingly. 2. Choose a platform: Choose an appropriate short video platform based on your target audience. The current mainstream short video platforms include Douyin, Kuaishou, Huoshan Video, etc.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to implement change event binding of select elements in jQuery How to implement change event binding of select elements in jQuery Feb 23, 2024 pm 01:12 PM

jQuery is a popular JavaScript library that can be used to simplify DOM manipulation, event handling, animation effects, etc. In web development, we often encounter situations where we need to change event binding on select elements. This article will introduce how to use jQuery to bind select element change events, and provide specific code examples. First, we need to create a dropdown menu with options using labels:

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What is the type of return value of Golang function? What is the type of return value of Golang function? Apr 13, 2024 pm 05:42 PM

Go functions can return multiple values ​​of different types. The return value type is specified in the function signature and returned through the return statement. For example, a function can return an integer and a string: funcgetDetails()(int,string). In practice, a function that calculates the area of ​​a circle can return the area and an optional error: funccircleArea(radiusfloat64)(float64,error). Note: If the function signature does not specify a type, a null value is returned; it is recommended to use a return statement with an explicit type declaration to improve readability.

A Deep Dive into Close Button Events in jQuery A Deep Dive into Close Button Events in jQuery Feb 24, 2024 pm 05:09 PM

In-depth understanding of the close button event in jQuery During the front-end development process, we often encounter situations where we need to implement the close button function, such as closing pop-up windows, closing prompt boxes, etc. When using jQuery, a popular JavaScript library, it becomes extremely simple and convenient to implement the close button event. This article will delve into how to use jQuery to implement close button events, and provide specific code examples to help readers better understand and master this technology. First, we need to understand how to define

How to build event-based applications using PHP How to build event-based applications using PHP May 04, 2024 pm 02:24 PM

Methods for building event-based applications in PHP include using the EventSourceAPI to create an event source and using the EventSource object to listen for events on the client side. Send events using Server Sent Events (SSE) and listen for events on the client side using an XMLHttpRequest object. A practical example is to use EventSource to update inventory counts in real time in an e-commerce website. This is achieved on the server side by randomly changing the inventory and sending updates, and the client listens for inventory updates through EventSource and displays them in real time.

C++ function types and characteristics C++ function types and characteristics Apr 11, 2024 pm 03:30 PM

C++ functions have the following types: simple functions, const functions, static functions, and virtual functions; features include: inline functions, default parameters, reference returns, and overloaded functions. For example, the calculateArea function uses π to calculate the area of ​​a circle of a given radius and returns it as output.

See all articles