


A brief analysis of the content between js event binding & event monitoring & event delegation
The content of this article is about a brief analysis of js event binding & event monitoring & event delegation. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.
1. Event binding
If you want JavaScript to respond to user operations, you must first bind an event handler to the DOM element. The so-called event processing function is a function that processes user operations. Different operations correspond to different names.
There are three commonly used methods of binding events:
(1) Bind events directly in the DOM
We can bind onclick on the DOM element , onmouseover, onmouseout, onmousedown, onmouseup, ondblclick, onkeydown, onkeypress, onkeyup, etc.
<input type="button" value="click me" onclick="hello()"><script> function hello(){ alert("hello world!"); } </script>
(2) Binding events in JavaScript code
Binding events in JavaScript code (i.e. within script tags) can separate JavaScript code from HTML tags and document structure Clear and easy to manage and develop.
<input type="button" value="click me" id="btn"><script> document.getElementById("btn").onclick = function(){ alert("hello world!"); } </script>
(3) Use event listening to bind events
Another way to bind events is to use addEventListener() or attachEvent() to bind the event listening function.
Event monitoring
Regarding event monitoring, the W3C specification defines three event stages, which are the capture stage, the target stage, and the bubbling stage.
W3C specification
element.addEventListener(event, function, useCapture)
event: (required) event name, supports all DOM events.
function: (required) Specifies the function to be executed when the event is triggered.
useCapture: (Optional) Specifies whether the event is executed in the capture or bubbling phase. true, capture. false, bubble. Default is false.
<input type="button" value="click me" id="btn1"><script> document.getElementById("btn1").addEventListener("click",hello); function hello(){ alert("hello world!"); } </script>
IE Standard
element.attachEvent(event, function)
event: (Required) Event type. Need to add "on", for example: onclick.
function: (required) Specifies the function to be executed when the event is triggered.
<input type="button" value="click me" id="btn2"><script> document.getElementById("btn2").attachEvent("onclick",hello); function hello(){ alert("hello world!"); } </script>
Advantages of event monitoring
1. Multiple events can be bound.
Conventional event binding only executes the last bound event. The event listener can execute multiple functions.
<input type="button" value="click me" id="btn4"><script> var btn4 = document.getElementById("btn4"); btn4.addEventListener("click",hello1); btn4.addEventListener("click",hello2); function hello1(){ alert("hello 1"); } function hello2(){ alert("hello 2"); } </script>
2. You can unbind the corresponding one
<input type="button" value="click me" id="btn5"><script> var btn5 = document.getElementById("btn5"); btn5.addEventListener("click",hello1);//执行了 btn5.addEventListener("click",hello2);//不执行 btn5.removeEventListener("click",hello2); function hello1(){ alert("hello 1"); } function hello2(){ alert("hello 2"); } </script>
Encapsulation of event monitoring
<input type="button" value="click me" id="btn5">//绑定监听事件 function addEventHandler(target,type,fn){ if(target.addEventListener){ target.addEventListener(type,fn); }else{ target.attachEvent("on"+type,fn); } }//移除监听事件 function removeEventHandler(target,type,fn){ if(target.removeEventListener){ target.removeEventListener(type,fn); }else{ target.detachEvent("on"+type,fn); } }
Event capture:Event capture instructions is from the document to the node that triggers the event, that is, from top to bottom to trigger the event.
Event bubbling: is a bottom-up process to trigger events. The third parameter of the bound event method is to control whether the event triggering sequence is event capture. true, event capture; false, event bubbling. The default is false, which means the event bubbles up.
<p id="parent"> <p id="child" class="child"></p> </p> document.getElementById("parent").addEventListener("click",function(e){ alert("parent事件被触发,"+this.id); }) document.getElementById("child").addEventListener("click",function(e){ alert("child事件被触发,"+this.id) }) child事件被触发,child parent事件被触发,parent
Conclusion: child first, then parent. Events are triggered in order from the inside out, which is called event bubbling.
Now change the value of the third parameter to true:
document.getElementById("parent").addEventListener("click",function(e){ alert("parent事件被触发,"+e.target.id); },true) document.getElementById("child").addEventListener("click",function(e){ alert("child事件被触发,"+e.target.id) },true)parent事件被触发,parentchild事件被触发,child
Conclusion: first parent, then child. The order of event triggering is changed from outside to inside, which is event capture.
Prevent events from bubbling and prevent default events:
event.stopPropagation() method: This is a method to prevent events from bubbling and prevent events from flowing to spread on the document, but the default event will still be executed. When you use this method, if you click on a connection, the connection will still be opened.
event.preventDefault() method: This is a method to prevent the default event. When this method is called, the connection will not be opened, but bubbling will occur, and the bubbling will be passed to the upper layer. Parent element
return false: This method is more violent. It will prevent event bubbling and prevent the default event. When this code is written, the connection will not be opened and the event will not be passed to the server. The parent element of one layer; it can be understood that return false is equivalent to calling event.stopPropagation() and event.preventDefault() at the same time
2. Event delegation
Event delegation is to use The principle of bubbling is to add events to parent elements or ancestor elements to trigger execution effects.
<input type="button" value="click me" id="btn6"> var btn6 = document.getElementById("btn6"); document.onclick = function(event){ event = event || window.event; var target = event.target || event.srcElement; if(target == btn6){ alert(btn5.value); } }
Advantages of event delegation
1. Improve JavaScript performance. Event delegation can significantly improve the processing speed of events and reduce memory usage
<ul id="list"> <li id="item1" >item1</li> <li id="item2" >item2</li> <li id="item3" >item3</li></ul><script> var item1 = document.getElementById("item1"); var item2 = document.getElementById("item2"); var item3 = document.getElementById("item3"); document.addEventListener("click",function(event){ var target = event.target; if(target == item1){ alert("hello item1"); }else if(target == item2){ alert("hello item2"); }else if(target == item3){ alert("hello item3"); } })</script>
2. Dynamically add DOM elements without modifying event bindings due to changes in elements.
<ul id="list"> <li id="item1" >item1</li> <li id="item2" >item2</li> <li id="item3" >item3</li></ul><script>var list = document.getElementById("list"); document.addEventListener("click",function(event){ var target = event.target; if(target.nodeName == "LI"){ alert(target.innerHTML); } }) var node=document.createElement("li"); var textnode=document.createTextNode("item4"); node.appendChild(textnode); list.appendChild(node); </script>
Related recommendations:
A brief discussion on jquery’s on() binding event and off() unbinding event
The above is the detailed content of A brief analysis of the content between js event binding & event monitoring & event delegation. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are 4 ways to bind events in jquery, namely: bind(), live(), delegate() and on() methods; the bind() method can only bind events to existing elements, while the live() ), on(), and delegate() all support event binding for newly added elements in the future.

When developing applications using UniApp, you may encounter the following error message: 'xxx' event is not bound. This is caused by UniApp's event binding mechanism, which needs to be set correctly to solve this problem. 1. Cause of the problem In UniApp, event binding of page components is completed through the v-on instruction. For example, add a button component to the template: <button@click="onClick">Click me</butto

How to effectively prevent event bubbling requires specific code examples. Event bubbling means that when an event on an element is triggered, the parent element will also receive the same event trigger. This event delivery mechanism sometimes brings problems to web development. Trouble, so we need to learn how to effectively stop events from bubbling up. In JavaScript, we can stop an event from bubbling by using the stopPropagation() method of the event object. This method can be called within an event handler to stop the event from propagating to the parent element.

Sorry, but I can't provide you with a complete code example. However I can provide you with a basic idea and sample code snippet for reference. The following is a simple example of combining JavaScript and Tencent Map to implement the map event monitoring function: //Introducing Tencent Map's API constscript=document.createElement('script');script.src='https://map.

The function of jquery binding event: Bind ordinary events to DOM nodes. When the DOM node is selected, bind the event to it to facilitate users to provide corresponding operations. jQuery provides four event binding methods, namely bind, live, delegate, and on, and the corresponding unlistening functions are unbind, die, undelegate, and off.

As a scripting language, JavaScript can bind events to elements on the page, so that when a specified event occurs, the corresponding event handler can be automatically called to handle the event. So how to add events to elements? The following article will introduce to you three ways to bind events in JS. I hope it will be helpful to you!

jQuery is a popular JavaScript library that is widely used to handle interactivity in web pages. Among them, event binding is one of the important functions of jQuery. Through event binding, responses to user interactions can be achieved. This article will explore jQuery event binding technology and give specific code examples. 1. The basic concept of event binding Event binding refers to adding an event listener on a DOM element to perform specified operations when a specific event occurs. In jQuery, select the desired

Vue is a popular JavaScript framework for building modern web applications. In Vue, we usually use directives to operate DOM elements. Among them, the "click" event is one of the commonly used instructions. However, in Vue applications, we often encounter situations where the "click" event binding is invalid. This article explains how to solve this problem. The first step in checking whether an element exists is to confirm whether the element to which you want to bind a "click" event exists. If the element does not exist,
