Home Web Front-end JS Tutorial Event delegation in javascript (picture and text tutorial)

Event delegation in javascript (picture and text tutorial)

May 19, 2018 pm 02:53 PM
javascript js Tutorial

This article mainly introduces relevant information on the detailed explanation of event delegation in javascript. Friends who need it can refer to it

I have seen an interview question these days, which is probably, asking you to give 1,000 li How should I add a click event? Most people's first impression may be to add one to each li. If this is the case, it is estimated that they will be GG during the interview. Here we have withdrawn our Event bubbling and capturing mechanisms, as well as event delegation mechanisms, let’s take a look at the above.

First let’s talk about event bubbling and event capturing mechanisms. Event bubbling was proposed by Microsoft. Event capture was proposed by Netscape. At that time, the two companies were at loggerheads. Later, W3C had no choice but to adopt a compromise method. When an event occurs, it is captured first and then bubbles up.

Usually , there are three ways to listen to events in js, namely:

 ele.addEventListener(type,listener,[useCapture]);//IE6~8 does not support

  ele.attachEvent('on' type,listener);//Supported by IE6~10, not supported by IE11

##  ele.onClick=function(){}; //All browsers support

The w3c specification defines three event stages, which are the capture stage, the target stage, and the bubbling stage. In the dom2 level regulations specified by w3c, the addEventListener is used to listen for events. So we will use addEventListener to explain. First of all, bubbles are just like when you throw a stone into the water, the bubbles in the water will pop up from below, which means that after the event is triggered, it will move from the direction of the child element to the parent element. Trigger, while the capture mechanism is just the opposite. The capture mechanism triggers events from the parent element to the child element, and the third parameter in the addEventListener function is used to determine whether to use the capture mechanism or the bubbling mechanism. When useCapture is true It is a capturing mechanism. When useCapture is false, it is a bubbling mechanism. Let’s take a look at the example:

Copy code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<p class="parent">

  <p class="child">

 

  </p>

</p>

<script>

  var parent = document.getElementsByClassName(&#39;parent&#39;)[0];

  var child = document.getElementsByClassName(&#39;child&#39;)[0];

 

  parent.addEventListener(&#39;click&#39;,function(){

    console.log("这里是父元素");

  },false);

  child.addEventListener(&#39;click&#39;,function(){

    console.log("这里是子元素");

  },false);

</script>

Copy after login

When we click on the child element it is Show the picture above. When we change false to true, we will find that the execution order will be reversed. This is the difference between event bubbling and capturing. They are just the opposite,

Then the disadvantage of using this binding mechanism is that it is very troublesome to bind events to each object. When we want to delete an event or change an event, it will be particularly cumbersome and more important. What's more, we have increased the association between JavaScript and DOM nodes, and if there is a circular reference, it is very likely to cause memory leaks. These are its drawbacks,

So one way to solve this drawback It is event delegation. This method allows you to avoid adding events to each node one by one. What it does is bind these listening events to the parent elements of these nodes. On the parent element, this The listening function automatically determines which child element triggered the event, so that it can operate on the child element that triggered the event. The example we give here is an example given by davidwalsh:

Now we have a The parent element ul and several li child elements,

1

2

3

4

5

6

7

8

<ul id="parent-list">

  <li id="post-1">Item 1</li>

  <li id="post-2">Item 2</li>

  <li id="post-3">Item 3</li>

  <li id="post-4">Item 4</li>

  <li id="post-5">Item 5</li>

  <li id="post-6">Item 6</li>

</ul>

Copy after login

What we want to achieve now is that when we click on each li node, the content in the li node will be output. According to the above writing, you can select After these li, add these methods to them, and then remove them when they are no longer needed. If there are 100 li or 1000 li, this will become your nightmare. A better solution is to give it to your parents. Add a listening event to the element. The next question is how to determine which li was clicked? We can judge the target of the current event in the listening event to determine whether it is the node we are looking for. Here we have a simple Example:

1

2

3

4

5

6

7

8

9

// 找到父元素,绑定一个监听事件

document.getElementById("parent-list").addEventListener("click", function(e) {

  // e.target是点击的元素

  // 如果它是li元素

  if(e.target && e.target.nodeName == "LI") {

    //

    console.log("List item ", e.target.id.replace("post-", ""), " was clicked!");

  }

});

Copy after login

When a click event occurs in ul, because addEventListener is a bubbling event by default, the listening event will be executed when the underlying event bubbles over. After the event is triggered, we will detect whether it is us. If the target element we are looking for is not the target element, it will be ignored. Then we can not only check whether the tag of the target element is the target element we need, but we can also detect it based on the attributes or class name of the target element, using ele. maeches API is used for processing.

1

2

3

4

5

6

document.getElementById("myp").addEventListener("click",function(e) {

  // e.target 就是当前被点击的元素

 if (e.target && e.target.matches("a.classA")) {

  console.log("Anchor element clicked!");

  }

});

Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Vue.jsDetailed explanation of the steps to develop mpvue framework

Loading and removal jsDetailed explanation of steps with css files

How to write JS when you need to traverse irregular multi-dimensional arrays

The above is the detailed content of Event delegation in javascript (picture and text tutorial). 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)

Tutorial on how to use Dewu Tutorial on how to use Dewu Mar 21, 2024 pm 01:40 PM

Dewu APP is currently a very popular brand shopping software, but most users do not know how to use the functions in Dewu APP. The most detailed usage tutorial guide is compiled below. Next is the Dewuduo that the editor brings to users. A summary of function usage tutorials. Interested users can come and take a look! Tutorial on how to use Dewu [2024-03-20] How to use Dewu installment purchase [2024-03-20] How to obtain Dewu coupons [2024-03-20] How to find Dewu manual customer service [2024-03-20] How to check the pickup code of Dewu [2024-03-20] Where to find Dewu purchase [2024-03-20] How to open Dewu VIP [2024-03-20] How to apply for return or exchange of Dewu

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

In summer, you must try shooting a rainbow In summer, you must try shooting a rainbow Jul 21, 2024 pm 05:16 PM

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

Tutorial on how to turn off the payment sound on WeChat Tutorial on how to turn off the payment sound on WeChat Mar 26, 2024 am 08:30 AM

1. First open WeChat. 2. Click [+] in the upper right corner. 3. Click the QR code to collect payment. 4. Click the three small dots in the upper right corner. 5. Click to close the voice reminder for payment arrival.

DisplayX (monitor testing software) tutorial DisplayX (monitor testing software) tutorial Mar 04, 2024 pm 04:00 PM

Testing a monitor when buying it is an essential part to avoid buying a damaged one. Today I will teach you how to use software to test the monitor. Method step 1. First, search and download the DisplayX software on this website, install it and open it, and you will see many detection methods provided to users. 2. The user clicks on the regular complete test. The first step is to test the brightness of the display. The user adjusts the display so that the boxes can be seen clearly. 3. Then click the mouse to enter the next link. If the monitor can distinguish each black and white area, it means the monitor is still good. 4. Click the left mouse button again, and you will see the grayscale test of the monitor. The smoother the color transition, the better the monitor. 5. In addition, in the displayx software we

What software is photoshopcs5? -photoshopcs5 usage tutorial What software is photoshopcs5? -photoshopcs5 usage tutorial Mar 19, 2024 am 09:04 AM

PhotoshopCS is the abbreviation of Photoshop Creative Suite. It is a software produced by Adobe and is widely used in graphic design and image processing. As a novice learning PS, let me explain to you today what software photoshopcs5 is and how to use photoshopcs5. 1. What software is photoshop cs5? Adobe Photoshop CS5 Extended is ideal for professionals in film, video and multimedia fields, graphic and web designers who use 3D and animation, and professionals in engineering and scientific fields. Render a 3D image and merge it into a 2D composite image. Edit videos easily

Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Mar 22, 2024 pm 12:21 PM

With the continuous development of smart phones, the functions of mobile phones have become more and more powerful, among which the function of taking long pictures has become one of the important functions used by many users in daily life. Long screenshots can help users save a long web page, conversation record or picture at one time for easy viewing and sharing. Among many mobile phone brands, Huawei mobile phones are also one of the brands highly respected by users, and their function of cropping long pictures is also highly praised. This article will introduce you to the correct method of taking long pictures on Huawei mobile phones, as well as some expert tips to help you make better use of Huawei mobile phones.

PHP Tutorial: How to convert int type to string PHP Tutorial: How to convert int type to string Mar 27, 2024 pm 06:03 PM

PHP Tutorial: How to Convert Int Type to String In PHP, converting integer data to string is a common operation. This tutorial will introduce how to use PHP's built-in functions to convert the int type to a string, while providing specific code examples. Use cast: In PHP, you can use cast to convert integer data into a string. This method is very simple. You only need to add (string) before the integer data to convert it into a string. Below is a simple sample code

See all articles