Home Web Front-end JS Tutorial Detailed explanation of JavaScript implementation of binding listening function examples for event handles

Detailed explanation of JavaScript implementation of binding listening function examples for event handles

Jan 19, 2018 am 10:47 AM
javascript js binding

This article mainly introduces the method of binding listening functions to event handlers in JavaScript. It analyzes the common techniques and precautions of JavaScript event binding in the form of examples. Friends in need can refer to it. I hope it can help everyone.

Binding event listening functions to Dom elements in JavaScript is a very common thing, but there are also many bugs here. Various browsers provide many methods for event binding, but only 3 are reliable:

1. Traditional binding method:


elem.onclick = function( event ){
  alert(event.type + 'this.innerHTML');
};
Copy after login

a. The traditional binding method is very simple and stable. This in the function body also points to the node that is processing the event (such as the node currently running the event handler).

b. An event handler of an element can only register one function. If registered repeatedly, overwriting will occur; moreover, the traditional binding method will only run in event bubbling.

2. W3C standard binding method:


var elem = document.getElementById('ID');
elem.addEventListener('click' ,
          function( event ){
            alert(event.type + ' ' + this.innerHTML + 1);
          } ,
          false  //冒泡阶段执行
);
elem.addEventListener('click' ,
          function( event ){
            alert(event.type + ' ' + this.innerHTML + 2);
          } ,
          false
);
Copy after login

a. This binding method supports both time processing capture and There are two stages of bubbling; the same event handler of the same element can register multiple listening functions; moreover, this inside the listening function points to the current element.

b. However, the popular IE browser does not support this registration method.

3. IE event handle registration method:


var elem = document.getElementById('a');
elem.attachEvent('onclick' ,
  function(){
    alert(window.event.srcElement.innerHTML + ' ' + this.innerHTML + 1);
  }
);
elem.attachEvent('onclick' ,
  function(){
    alert(window.event.srcElement.innerHTML + ' ' + this.innerHTML + 2);
  }
);
Copy after login

a. This binding method can register the same event handle repeatedly.

b. IE's event model does not support event capture; this in the listening function body does not point to the current element, and window.event.srcElement points to the node where the event occurred, not the current node, and in There is no equivalent DOM currentTarget property in IE's event object.

4. Cross-browser method one:


function addEvent(element, type, handler) {
 if (!handler.guid)handler.guid = addEvent.guid++;
 if (!element.events) element.events = {};
 var handlers = element.events[type];
 if (!handlers) {
  handlers = element.events[type] = {};
  if (element["on" + type]) {
   handlers[0] = element["on" + type];
  }
 }
 handlers[handler.$$guid] = handler;
 element["on" + type] = handleEvent;
};
addEvent.guid = 1;
function removeEvent(element, type, handler) {
 if (element.events && element.events[type]) {
  delete element.events[type][handler.$$guid];
 }
};
function handleEvent(event) {
 var returnValue = true;
 event = event || fixEvent(window.event);
 var handlers = this.events[event.type];
 for (var i in handlers) {
  this.$$handleEvent = handlers[i];
  if (this.$$handleEvent(event) === false) {
   returnValue = false;
  }
 }
 return returnValue;
};
function fixEvent(event) {
 event.preventDefault = fixEvent.preventDefault;
 event.stopPropagation = fixEvent.stopPropagation;
 return event;
};
fixEvent.preventDefault = function() {
 this.returnValue = false;
};
fixEvent.stopPropagation = function() {
 this.cancelBubble = true;
};
Copy after login

The above code is from Dean EdwardsaddEvent/removeEven

5. Cross-browser method two:


function addEvent( obj, type, fn ) {
 if ( obj.attachEvent ) {
  obj['e'+type+fn] = fn;
  obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
  obj.attachEvent( 'on'+type, obj[type+fn] );
 } else
  obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
 if ( obj.detachEvent ) {
  obj.detachEvent( 'on'+type, obj[type+fn] );
  obj[type+fn] = null;
 } else
  obj.removeEventListener( type, fn, false );
}
Copy after login

In addition, the event stream can be divided into bubbling events and capture events, HTML Most elements contain their own default behavior, such as hyperlinks, submit buttons, etc. We can prevent its default behavior by adding "return false" to the binding event. If you are interested in Pinyin, please refer to the relevant introduction on the detailed introduction of event bubbling and event capture in JS on this website.

Related recommendations:

vue monitors scrolling events and a detailed explanation of ceiling or fixed position display of an element

How to implement ReactJS monitoring Page scroll event

Detailed explanation of event listening and event publishing usage examples in Node.js

The above is the detailed content of Detailed explanation of JavaScript implementation of binding listening function examples for event handles. 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)

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to bind a sub-account on Xiaohongshu? How does it check whether the account is normal? How to bind a sub-account on Xiaohongshu? How does it check whether the account is normal? Mar 21, 2024 pm 10:11 PM

In today's era of information explosion, the construction of personal brand and corporate image has become increasingly important. As the leading fashion life sharing platform in China, Xiaohongshu has attracted a large number of user attention and participation. For those users who want to expand their influence and improve the efficiency of content dissemination, binding sub-accounts has become an effective means. So, how does Xiaohongshu bind a sub-account? How to check whether the account is normal? This article will answer these questions for you in detail. 1. How to bind a sub-account on Xiaohongshu? 1. Log in to your main account: First, you need to log in to your Xiaohongshu main account. 2. Open the settings menu: click "Me" in the upper right corner, and then select "Settings". 3. Enter account management: In the settings menu, find the "Account Management" or "Account Assistant" option and click

Steps and methods to bind Douyin in Toutiao Steps and methods to bind Douyin in Toutiao Mar 22, 2024 pm 05:56 PM

1. Open Toutiao. 2. Click My in the lower right corner. 3. Click [System Settings]. 4. Click [Account and Privacy Settings]. 5. Click the button on the right side of [Douyin] to bind Douyin.

How to bind the Cainiao app to Pinduoduo? How to add the Cainiao Wrap to Pinduoduo platform? How to bind the Cainiao app to Pinduoduo? How to add the Cainiao Wrap to Pinduoduo platform? Mar 19, 2024 pm 02:30 PM

The Cainiao app is a platform that can provide you with various logistics information. The functions here are very powerful and easy to use. If you have any logistics-related problems, they can be solved here. Anyway, it can bring you a The one-stop service can solve everything in time. Checking the express delivery, picking up the express delivery, sending the express delivery, etc. are all without any problems. We have cooperated with various platforms and all the information can be queried. However, sometimes It will happen that the goods purchased on Pinduoduo cannot display the logistics information. In fact, you need to manually bind Pinduoduo to achieve this. The specific methods have been sorted out below, and everyone can take a look. . How to bind Cainiao to Pinduoduo account: 1. Open Cainiao APP and go to the main page

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

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 bind the Cainiao APP to Pinduoduo How to bind the Cainiao APP to Pinduoduo How to bind the Cainiao APP to Pinduoduo How to bind the Cainiao APP to Pinduoduo Mar 19, 2024 pm 05:16 PM

Do you know how to bind Pinduoduo when using Cainiao Wrap? The official version of Cainiao Wrap App does not automatically synchronize some Pinduoduo’s logistics information on this platform. All we need to do is You can copy the order number or check your mobile phone to see if there is any express delivery information. Of course, these all need to be completed manually. If you want to know more, come and take a look with the editor. How to bind the Cainiao APP to Pinduoduo 1. Open the Cainiao APP and click "Package Guide" in the upper left corner of the main page. 2. In the interface, there are many shopping websites, and accounts can be bound. 3. Click to import other e-commerce platforms. 4. User authorization: Click Pinduoduo to go to the interface

See all articles