How to use JS to add events to dynamic elements
This time I will show you how to operate JS to add events to dynamic elements. What are the precautions for operating JS to add events to dynamic elements? The following is a practical case, let’s take a look.
We sometimes create some elements through js in daily development, but if you use the original for loop to add events to the created nodes, it often does not work:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js动态添加事件</title> </head> <body> <ul id="out-ul"> <li class="out-li">123</li> <li class="out-li">123</li> <li class="out-li">123</li> </ul> <button id="btn">添加</button> <script> document.getElementById('btn').addEventListener('click',function(){ var htmlFragment='<li>我是新增的li</li>'; var addLi=document.createElement('li'); addLi.innerHTML=htmlFragment; outUl.appendChild(addLi); },false); var outUl=document.getElementById('out-ul') var outLi=outUl.getElementsByClassName('out-li'); for(var i=0;i<outLi.length;i++){ outLi[i].onclick=function(){ alert(1); } } </script> </body> </html>
Running effect:
For example, the events added to li through the for loop cannot be bound to the newly added li. The detailed reasons will not be explained here. So how to solve this? In fact, the method is also simple, which is to solve it through event delegation. Directly enter the code. The above code is simply modified:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>www.jb51.net js动态添加事件</title> </head> <body> <ul id="out-ul"> <li class="out-li">123</li> <li class="out-li">123</li> <li class="out-li">123</li> </ul> <button id="btn">添加</button> <script> var outUl=document.getElementById('out-ul') var outLi=outUl.getElementsByClassName('out-li'); document.getElementById('btn').addEventListener('click',function(){ var htmlFragment='<li>我是新增的li</li>'; var addLi=document.createElement('li'); addLi.innerHTML=htmlFragment; outUl.appendChild(addLi); },false); outUl.addEventListener('click',function(e){ e=e || window.event;//兼容ie alert(e.target.innerHTML); }, false); </script> </body> </html>
I believe you have mastered the method after reading the case in this article. More Please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to use jquery filter() in actual projects
##nodejs server.js to create a Web server
The above is the detailed content of How to use JS to add events to dynamic elements. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

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

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

jQuery is a popular JavaScript library that can be used to simplify DOM manipulation, event handling, animation effects, etc. In web development, we often encounter situations where we need to change event binding on select elements. This article will introduce how to use jQuery to bind select element change events, and provide specific code examples. First, we need to create a dropdown menu with options using labels:

In-depth understanding of the close button event in jQuery During the front-end development process, we often encounter situations where we need to implement the close button function, such as closing pop-up windows, closing prompt boxes, etc. When using jQuery, a popular JavaScript library, it becomes extremely simple and convenient to implement the close button event. This article will delve into how to use jQuery to implement close button events, and provide specific code examples to help readers better understand and master this technology. First, we need to understand how to define

Methods for building event-based applications in PHP include using the EventSourceAPI to create an event source and using the EventSource object to listen for events on the client side. Send events using Server Sent Events (SSE) and listen for events on the client side using an XMLHttpRequest object. A practical example is to use EventSource to update inventory counts in real time in an e-commerce website. This is achieved on the server side by randomly changing the inventory and sending updates, and the client listens for inventory updates through EventSource and displays them in real time.

js methods to refresh the current page: 1. location.reload(); 2. location.href; 3. location.assign(); 4. window.location. Detailed introduction: 1. location.reload(), use the location.reload() method to reload the current page; 2. location.href, you can refresh the current page by setting the location.href attribute, etc.
