search
HomeWeb Front-endJS TutorialEvent delegation in javascript (picture and text tutorial)
Event delegation in javascript (picture and text tutorial)May 19, 2018 pm 02:53 PM
javascriptjsTutorial

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

<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>

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,

<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>

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:

// 找到父元素,绑定一个监听事件
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!");
  }
});

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.

document.getElementById("myp").addEventListener("click",function(e) {
  // e.target 就是当前被点击的元素
 if (e.target && e.target.matches("a.classA")) {
  console.log("Anchor element clicked!");
  }
});

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
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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment