Table of Contents
Definition of event delegation:
Advantages of event delegation:
In the following code, the effect to be achieved by the p tag is that the background color changes to red when the mouse clicks on the p tag. The following are js and jq The processing method
1. js event delegation
2 , jquery event delegation:
Home Web Front-end JS Tutorial javascript event delegation and jquery event delegation

javascript event delegation and jquery event delegation

Jul 01, 2020 am 09:46 AM
javascript

After New Year’s Day, the first article of the New Year.
Original Intention: Many interviews will involve event commissioning. I have read many blog posts one after another. They are all very good and each has its own merits. I have to think about it myself, for my own review in the future, and at the same time To provide front-end partners who are looking for a job with a seemingly more comprehensive place to interpret event delegation to understand its principles, this article summarizes two versions of event delegation: javascript, jquery;

Definition of event delegation:

Use event bubbling, onlyspecify an event handler to manage all events of a certain type.

Advantages of event delegation:

  • The number of event handlers added to the page in js directly affects the running performance of the web page. Because each event processing function is an object, the object will occupy memory, and the more objects in the memory, the result will be worse performance; and the more times the DOM is accessed, it will cause the structure to be redrawn or redrawn. The number of rows will also increase, which will delay the interactive readiness time of the entire page;

  • For new DOM elements added after the page is processed, event delegation can be used to provide new DOM elements for the new DOM elements. Elements are added and subtracted together with event handlers;

In the following code, the effect to be achieved by the p tag is that the background color changes to red when the mouse clicks on the p tag. The following are js and jq The processing method

    <p>
      </p><p>第一个p</p>
      <p>第二个p</p>
      <p>第三个p</p>
      <p>
          </p><p>这是子集菜单</p>
          <p>我是子集的p
              </p><p>我是子集的p</p>
          
      
    
    <button>点击加一</button>
  
Copy after login

1. js event delegation

If event delegation is not used in js: get all the p tags in the page and then use a for loop to traverse and add event processing functions to each element

let nodes = document.getElementById("nodes");
    let ps = document.getElementsByTagName("p");
    console.log(ps);
    let btn = document.getElementsByTagName("button")[0];
    let inner = 33;

    btn.onclick = function() {
      inner++;
      let p = document.createElement("p");
      p.innerHTML = inner + "新增的p标签啊";
      nodes.appendChild(p);
      console.log(ps);
    };
    for (let i= 0;i<ps.length><p>At this time, after running it in the browser, I tested it and found the result as shown in Figure 1; </p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/376/157/896/1593567746839219.png" class="lazy" title="1593567746839219.png" alt="javascript event delegation and jquery event delegation"></p><p>So how can js be given to new users without event delegation? What about adding event handlers for added tags? The solution is as follows: </p><pre class="brush:php;toolbar:false">let nodes = document.getElementById("nodes");
    let ps = document.getElementsByTagName("p");
    console.log(ps);
    let btn = document.getElementsByTagName("button")[0];
    let inner = 33;

    btn.onclick = function () {
        inner++;
        let p = document.createElement("p");
        p.innerHTML = inner + "新增的p标签啊";
        nodes.appendChild(p);
        addEvent();//将新dom元素增加到页面后再执行循环函数
        console.log(ps);
    };

    function addEvent() {
        for (let i = 0; i <p>At this time, the browser runs as shown in Figure 2:</p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/129/624/157/1593567770605067.png" class="lazy" title="1593567770605067.png" alt="javascript event delegation and jquery event delegation"></p><p>At this time, although adding events for new dom elements is solved There is a problem with the processing function, but after careful consideration, its performance has declined compared to before. The reason is that another event processing function (object) has been added, which once again takes up memory; therefore, events will be used at this time Delegation, the advantages of event delegation are also reflected at this time: </p><pre class="brush:php;toolbar:false">let nodes = document.getElementById("nodes");
    let ps = document.getElementsByTagName("p");
    console.log(ps);
    let btn = document.getElementsByTagName("button")[0];
    let inner = 33;

    btn.onclick = function () {
        inner++;
        let p = document.createElement("p");
        p.innerHTML = inner + "新增的p标签啊";
        nodes.appendChild(p);
        console.log(ps);
    };
//事件委托,为nodes指定一个事件处理函数,处理nodes下为p标签的所有元素的cilck事件
    nodes.onclick= function(e){
        let ev = e || window.event
        let target = ev.target || ev.srcElement //srcElement IE浏览器
        //这里要判被处理元素节点的名字,也可以增加相应的判断条件 target.nodeName.toLowerCase() == 'p'||target.nodeName.toLowerCase() == 'span',但是要注意不要使用父级元素的名称,因为再点击子元素之间的空气的时候,由于事件冒泡他会给父级元素也增加相应的事件处理函数;因为返回的节点名称一般都是大写,所以这时要用toLowerCase()处理一下;
        if(target.nodeName.toLowerCase() == 'p'){ 
            target.style.background = 'green'
        }
    }
Copy after login

At this time, the result of running in the browser is shown in Figure 3:

javascript event delegation and jquery event delegation

2 , jquery event delegation:

Compared with js event delegation, the advantages of jquery event delegation: When executing event delegation, only the child element will trigger the event function, and the parent element executed on its behalf will not. The event function will be triggered, so there is no need to judge the name of the element node; (Note that the event delegation method here is on, if the bind method is used, the parent element will trigger the event function)
All nodes under the node here The child nodes labeled p are all assigned event processing functions; the child nodes here can also be multiple similar to 'p, span'. It should be noted that the same labels as nodes cannot be written here, otherwise the intervals between click elements The event processing function will be assigned to p under nodes; for example, Example 2:
Example 1:

let inner = 33;
//这里nodes节点下所有标签为p的子节点都被赋予事件处理函数;这里的子节点还可以是多个类似' p,span',需要注意这里面也不可以写同nodes一样的标签,否则点击元素之间的间隔会给nodes下的p赋予事件处理函数
$('#nodes').on('click','p',function(e){
        let target = $(e.target)
        target.css('backgroundColor','red')
    })
    $('button').click(()=>{
        inner++;
        $('#nodes').append($('<p>我是新增加的p标签'+inner+'</p>'))
    })
Copy after login

The effect of browser operation is shown in Figure 4:

javascript event delegation and jquery event delegation

##Example 2:

    <p>
        </p><p>第一个p</p>
        <p>第二个p</p>
        <p>第三个p</p>
        <span>span</span>
        <p>
            </p><p>这是子集菜单</p>
            <p>我是子集的p
                </p><p>我是子集的p</p>
            
        
    
    <button>点击加一</button>

<script>
let inner =33;
$(&#39;#nodes&#39;).on(&#39;click&#39;,&#39;p,p,span&#39;,function(e){
        let target = $(e.target)
        target.css(&#39;backgroundColor&#39;,&#39;red&#39;)
    })
    $(&#39;button&#39;).click(()=>{
        inner++;
        $(&#39;#nodes&#39;).append($(&#39;<p>我是新增加的p标签&#39;+inner+&#39;&#39;))
    })
</script>
Copy after login
The browser running effect is shown in Figure 5:

javascript event delegation and jquery event delegation

Event delegation is not just for processing one type of DOM operation, it can perform functions such as addition, deletion, modification, and query:

js event delegation: different operations

    <p>
        <input>
        <input>
    </p>
    <p>

    </p>

<script></script>
<script>
    let events = document.getElementById(&#39;events&#39;);
    let content = document.getElementById(&#39;content&#39;);
    events.onclick=function(e){
        let ev = e || window.event;
        let target = ev.target || ev.srcElement;
        if(target.nodeName.toLowerCase()==&#39;input&#39;){
            switch(target.id){
                case &#39;addHandle&#39;:
                return addEvent();
                break
                case &#39;deleteHandle&#39;:
                return deleteEvent();
                break
            }
        }
    }
    function addEvent(){
        let add = document.createElement(&#39;p&#39;)
        add.innerHTML = &#39;这是增加按钮&#39;
        content.appendChild(add)
    }
    function deleteEvent(){
        let del = document.createElement(&#39;p&#39;)
        del.innerHTML = &#39;这是删除按钮&#39;
        content.appendChild(del)
    }
</script>
Copy after login

Effects in the browser As shown in Figure 6:

javascript event delegation and jquery event delegation

jquery event delegation: different operations

$('#events').on('click','input',(e)=>{
        let target = $(e.target);
        switch(target[0].id){
                case 'addHandle':
                return addEvent();
                break
                case 'deleteHandle':
                return deleteEvent();
                break
        }
    })
    function addEvent(){
        $('#content').append($('<p>这是增加按钮</p>'))
    }
    function deleteEvent(){
        $('#content').append($('<p>这是删除按钮</p>'))
    }
Copy after login

The effect in the browser is as shown in Figure 7:

javascript event delegation and jquery event delegation

If there is any untruth in this article, I hope the experts will give me some pointers. Discussions are welcome!

Recommended tutorial: "

JS Tutorial"

The above is the detailed content of javascript event delegation and jquery event delegation. 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)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

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 use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles