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>
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/imghwm/default1.png" data-src="https://img.php.cn/upload/image/376/157/896/1593567746839219.png?x-oss-process=image/resize,p_40" 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/imghwm/default1.png" data-src="https://img.php.cn/upload/image/129/624/157/1593567770605067.png?x-oss-process=image/resize,p_40" 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' } }
At this time, the result of running in the browser is shown in Figure 3:
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>')) })
The effect of browser operation is shown in Figure 4:
##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; $('#nodes').on('click','p,p,span',function(e){ let target = $(e.target) target.css('backgroundColor','red') }) $('button').click(()=>{ inner++; $('#nodes').append($('<p>我是新增加的p标签'+inner+'')) }) </script>The browser running effect is shown in Figure 5:
<p>
<input>
<input>
</p>
<p>
</p>
<script></script>
<script>
let events = document.getElementById('events');
let content = document.getElementById('content');
events.onclick=function(e){
let ev = e || window.event;
let target = ev.target || ev.srcElement;
if(target.nodeName.toLowerCase()=='input'){
switch(target.id){
case 'addHandle':
return addEvent();
break
case 'deleteHandle':
return deleteEvent();
break
}
}
}
function addEvent(){
let add = document.createElement('p')
add.innerHTML = '这是增加按钮'
content.appendChild(add)
}
function deleteEvent(){
let del = document.createElement('p')
del.innerHTML = '这是删除按钮'
content.appendChild(del)
}
</script>
Effects in the browser As shown in Figure 6: $('#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>'))
}
The effect in the browser is as shown in Figure 7: 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!

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor
