Home Web Front-end JS Tutorial A brief discussion on several methods of Javascript event handlers_javascript skills

A brief discussion on several methods of Javascript event handlers_javascript skills

May 16, 2016 pm 05:52 PM
event handling

An event is some action performed by the user or the browser itself. For example, click and mouseover are the names of events. The function corresponding to an event is called an event handler (or event listener). There are several ways to specify handlers for events.
1: HTML event handler.
For example:

Copy code The code is as follows:




I believe this method is currently used more often by all of us, but specifying the event handler in html There are two disadvantages.
(1) First of all: there is a time difference problem. For this example, assuming that the show() function is defined below the button and at the bottom of the page, if the user clicks the button before the page parses the show() function, an error will occur;
(2) The second disadvantage is that html is tightly coupled with javascript code. If you want to change the time handler, you need to change two places: html code and javascript code.
As a result, many developers abandon HTML event handlers and instead use JavaScript to specify event handlers.
Two: Javascript designated event handler
Javascript designated event handler includes three methods:
(1): DOM level 0 event handler
Such as:
Copy code The code is as follows:

var btn=document.getElementById("mybtn"); //Get the Reference of the button
btn.onclick=function(){
alert('clicked');
alert(this.id); // mybtn

in this way The added event handler will be processed during the bubbling phase of the event flow.
Delete the event handler specified by the DOM0 level method:
btn.onclick=null; // Delete the event handler
}
(2):DOM2 level event handler
DOM2 level event Two methods are defined to handle the operation of specifying and removing event handlers: addEventListener() and removeEventListener(). These two methods are included in all DOM nodes, and they both accept 3 parameters: the name of the event to be handled, the function as the event handler, and a Boolean value. If the last parameter is true, it means that the event handler is called in the capture phase; if it is fasle, it means that the event handler is called in the bubbling phase.
For example:
Copy code The code is as follows:

var btn=document.getElementById( "mybtn");
btn.addEventListener("click",function(){
alert(this.id);
},false);

Use DOM2 level The main benefit of event handlers is that you can add multiple event handlers.
For example:
Copy code The code is as follows:

var btn=document.getElementById( "mybtn");
btn.addEventListener("click",function(){
alert(this.id);
},false);
btn.addEventListener("click",function (){
alert("hello world!");
},false);

Two event handlers are added here for the button. The two event handlers are fired in the order they occur.
Time handlers added through addEventListener() can only be removed using removeEventListener(). The parameters passed in when removing are the same as those used when adding. This also means that anonymous functions added through addEventListener() cannot be removed.
For example:
Copy code The code is as follows:

var btn=document.getElementById( "mybtn");
btn.addEventListener("click",function(){
alert(this.id);
},false);
//Remove
btn. removeEventListener("click",function(){ //Writing like this is useless (because the second time is a completely different function than the first time)
alert(this.id);
}, false);

Solution:
Copy the code The code is as follows:

var btn=document.getElementById("mybtn");
var hander=function(){
alert(this.id);
};
btn.addEventListener("click" ,hander,false);

btn.removeEventListener("click",hander,false); // Valid

Note: Our third parameter here is all false, which is added during the bubbling stage. In most cases, event handlers are added to the bubbling stage of the event flow, so as to maximize compatibility with various browsers.
3: IE event handler
IE implements 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 IE only supports time bubbling, all event handlers added through attachEvent() will be added to the bubbling stage.
For example:

Three:
Copy code The code is as follows:

var btn=document.getElementById("mybtn");
btn.attachEvent("onclick",function(){
alert("clicked");
})

Note: The first parameter of the attachEvent() function is "onclick", not "click" in the DOM's addEventListener(). The
attachEvent() method can also be used to add multiple event handlers to an element.
For example:
Copy code The code is as follows:

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

AttachEvent() is called twice here, adding two different event handlers for the same button . However, unlike DOM methods, these event handlers are not executed in the order in which they were added, but are fired in the reverse order. Click the button in this example: the first thing you see is "hello world", and then "clicked".
Events added using attachEvent() can be removed by detachEvent(), provided that the same parameter.
Copy code The code is as follows:

var btn=document.getElementById("mybtn");
var hander=function(){
alert("clicked");
}
btn.detachEvent("onclick",hander}); // Remove

The above three methods are currently the main event handler methods. When you see this, you will definitely think that since different browsers will have different differences, how to ensure cross-browser event handlers?
In order to handle events in a cross-browser manner, many developers use Javascript libraries that can isolate browser differences, and some developers develop the most appropriate event handling methods themselves.
An EventUtil object is provided here, which can be used to handle differences during browsing:
Copy code The code is as follows:

var EventUtil = {
addHandler: function(element, type, handler){ // This method accepts 3 parameters: the element to be operated on, the event name and the event handler function
if (element.addEventListener){ //Check whether the passed in element has a DOM2 level method
element.addEventListener(type, handler, false); // If it exists, use this method
} else if (element .addEvent){ // If there is an IE method
element.attachEvent("on" type, handler); // then use the IE method. Note that the event type here must be prefixed with "on".
} else { // The last possibility is to use DOM0 level
element["on" type] = hander;
}
},

removeHandler: function(element, type, handler){ // This method is to delete the previously added event handler
if (element.removeEventListener){ //Check whether the passed-in element exists DOM2 level method
element.removeEventListener(type, handler, false); // If it exists, use this method
} else if (element.detachEvent){ // If it exists, IE's method
element.detachEvent("on" type, handler); // Then use the IE method. Note that the event type here must be prefixed with "on".
} else { // The last possibility is to use DOM0 and methods (in modern browsers, the code here should not be executed)
element["on" type] = null;
}
}
};

You can use the EventUtil object as follows:
Copy codeThe code is as follows:

var btn =document.getElementById("mybtn");
var hander= function(){
alert("clicked");
};
//Omitted here Part of the code is omitted
EventUtil.addHandler(btn,"click",hander);
//Part of the code is omitted here
EventUtil.removeHandler(btn,"click",hander); //Before removal The added event handler

is visible. It is very convenient to use addHandler and removeHandler to add and remove event handlers.
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Python GUI programming: Get started quickly and easily create interactive interfaces Python GUI programming: Get started quickly and easily create interactive interfaces Feb 19, 2024 pm 01:24 PM

A brief introduction to python GUI programming GUI (Graphical User Interface, graphical user interface) is a way that allows users to interact with computers graphically. GUI programming refers to the use of programming languages ​​to create graphical user interfaces. Python is a popular programming language that provides a rich GUI library, making Python GUI programming very simple. Introduction to Python GUI library There are many GUI libraries in Python, the most commonly used of which are: Tkinter: Tkinter is the GUI library that comes with the Python standard library. It is simple and easy to use, but has limited functions. PyQt: PyQt is a cross-platform GUI library with powerful functions.

How to manage a complete circular queue of events in C++? How to manage a complete circular queue of events in C++? Sep 04, 2023 pm 06:41 PM

Introduction CircularQueue is an improvement on linear queues, which was introduced to solve the problem of memory waste in linear queues. Circular queues use the FIFO principle to insert and delete elements from it. In this tutorial, we will discuss the operation of a circular queue and how to manage it. What is a circular queue? Circular queue is another type of queue in data structure where the front end and back end are connected to each other. It is also known as circular buffer. It operates similarly to a linear queue, so why do we need to introduce a new queue in the data structure? When using a linear queue, when the queue reaches its maximum limit, there may be some memory space before the tail pointer. This results in memory loss, and a good algorithm should be able to make full use of resources. In order to solve the waste of memory

Event processing library in PHP8.0: Event Event processing library in PHP8.0: Event May 14, 2023 pm 05:40 PM

Event processing library in PHP8.0: Event With the continuous development of the Internet, PHP, as a popular back-end programming language, is widely used in the development of various Web applications. In this process, the event-driven mechanism has become a very important part. The event processing library Event in PHP8.0 will provide us with a more efficient and flexible event processing method. What is event handling? Event handling is a very important concept in the development of web applications. Events can be any kind of user row

What is the meaning of bubbling events What is the meaning of bubbling events Feb 19, 2024 am 11:53 AM

Bubbling events mean that in web development, when an event is triggered on an element, the event will propagate to upper elements until it reaches the document root element. This propagation method is like a bubble gradually rising from the bottom, so it is called a bubbling event. In actual development, knowing and understanding how bubbling events work is very important to handle events correctly. The following will introduce the concept and usage of bubbling events in detail through specific code examples. First, we create a simple HTML page with a parent element and three children

Practical applications of event bubbling and applicable event types Practical applications of event bubbling and applicable event types Feb 18, 2024 pm 04:19 PM

Application scenarios of event bubbling and the types of events it supports. Event bubbling means that when an event on an element is triggered, the event will be passed to the parent element of the element, and then to the ancestor element of the element until it is passed to the root node of the document. It is an important mechanism of the event model and has a wide range of application scenarios. This article will introduce the application scenarios of event bubbling and explore the types of events it supports. 1. Application scenarios Event bubbling has a wide range of application scenarios in web development. Here are several common application scenarios. form validation in form

In-depth study of the key code implementation of PHP and Vue in the brain map function In-depth study of the key code implementation of PHP and Vue in the brain map function Aug 27, 2023 pm 12:15 PM

In-depth study of the key code implementation of PHP and Vue in the brain map function Summary: This article will delve into the key code implementation of PHP and Vue in the realization of the mind map function. Brain mapping is a graphical tool commonly used to display thinking structures and relationships. It is widely used in fields such as project planning, knowledge management, and information organization. By learning the relevant knowledge of PHP and Vue, we can implement a simple yet powerful brain mapping application. Understand PHPPHP is a commonly used server-side scripting language. It is easy to learn and highly scalable

Java Error: JavaFX Event Handling Error, How to Handle and Avoid Java Error: JavaFX Event Handling Error, How to Handle and Avoid Jun 24, 2023 pm 10:49 PM

As a popular programming language, Java often encounters various errors and problems during the development process. Among them, JavaFX event handling errors are a common problem, which may cause the application to crash or fail. This article will introduce the causes, solutions and preventive measures of JavaFX event processing errors to help developers avoid and deal with such errors. Error causes JavaFX event processing errors are usually caused by the following reasons: 1) Code errors: When writing JavaFX code, code errors often occur

Analysis of v-on directive in Vue: how to handle form submission events Analysis of v-on directive in Vue: how to handle form submission events Sep 15, 2023 am 09:12 AM

Analysis of the v-on directive in Vue: How to handle form submission events In Vue.js, the v-on directive is used to bind event listeners and can capture and process various DOM events. Among them, processing form submission events is one of the common operations in Vue. This article will introduce how to use the v-on directive to handle form submission events and provide specific code examples. First of all, it is necessary to clarify that the form submission event in Vue refers to the event triggered when the user clicks the submit button or presses the Enter key. In Vue, you can pass

See all articles