1: What is event delegation?
Event delegation uses event bubbling to specify only one event handler to manage all events of a certain type.
2: Why use event delegation?
1. The number of event handlers added to the page in JavaScript is directly related to the overall running performance of the page. why? Because each event handling function is an object, the object will occupy memory. The more objects in the memory, the worse the performance. In addition, the number of DOM visits caused by having to specify all event handlers in advance will delay the overall page's interactive readiness time.
2. Adding events one by one to tables with many data and long lists is simply a nightmare. Therefore, event delegation can greatly improve the running performance of the page and reduce the workload of developers.
3: Example in JavaScript
We take the following HTML code as an example, and use event delegation to realize that when the mouse clicks on a li element, The background of the li element turns red.
<ul id = "lists"> <li>列表1</li> <li>列表2</li> <li>列表3</li> <li>列表4</li> <li>列表5</li> <li>列表6</li> </ul>
The following is the JavaScript code:
var lists = document.getElementById("lists"); lists.addEventListener("click",function(event){ var target = event.target; //防止父元素ul也触发事件 if(target.nodeName == "LI"){ target.style.backgroundColor = "red"; } })
Click List 4 to achieve the effect:
Four: Examples in jQuery
The event delegation methods in jQuery are relatively rich. Let’s take the same example:
1. Use the on method, the code is as follows:
$(function(){ $("#lists").on("click","li",function(event){ var target = $(event.target); target.css("background-color","red"); }) })
2. Use the delegate() method, the code is as follows:
$(function(){ $("#lists").delegate("li","click",function(event){ var target = $(event.target); target.css("background-color","red"); }) })
on() method and delegate() method are very similar to the writing of event delegation. And when executing event delegation, only the child element (li in this article) will trigger the event, and the parent element (ul in this article) will not trigger the event, so we do not need to judge the element node name that triggers the event. This One thing that is significantly better than native JavaScript.
3. Use the bind() method, the code is as follows:
$(function(){ $("#lists").bind("click","li",function(event){ var target = $(event.target); if(target.prop("nodeName")=="LI"){ target.css("background-color","red");} }) })
The bind() method is the same as the native JavaScript implementation method. When the parent element executes the event on behalf of the child element, the parent element will also Trigger an event, so we need to determine the element name that triggers the event. In addition, when using the bind() method to bind events to elements, please note that it can only add events to existing DOM elements and cannot add events to future DOM elements.
Element addition event. If you want to add DOM elements frequently and bind events to the newly added DOM elements, use live(), delegate(), on() and other methods. Since jQuery does not recommend the live() and delegate() methods since jQuery 1.7, you should still use the on() method.
The above is the detailed content of Event delegation in JavaScript (jQuery). For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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.

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