


Detailed explanation of JavaScript implementation of binding listening function examples for event handles
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'); };
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 );
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); } );
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; };
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 ); }
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:
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!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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.
