How to add elements dynamically in JS
This article mainly introduces to you the relevant information about the repeated execution of programs caused by dynamically adding elements and binding events in JS. The article introduces it in detail through sample code, which has certain reference value for everyone's study or work. Friends who need it can come and take a look below.
Preface
This article mainly shares with you the bug encountered some time ago. This bug is about jquery’s on method binding interactive events. Code similar to $('#point').on('click','.read-more',function () {})
causes repeated execution of the program. Many people wrote in the article When we arrived, we also talked about using the off method to unbind, but they failed to point out the essence of the problem. They almost ignored that the essence of the problem was actually caused by event delegation.
Without further ado, here are the codes I see every day:
##The first type:
$(document).on('click', function (e) { consol.log('jquery事件绑定') });
Second type:
document.addEventListener('click',function (e) { consol.log('原生事件绑定') });
Third type:
var id = setInterval(function () { console.log('定时器循环事件绑定') },1000);
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <button class="add_but">点击</button> <p id="point">fdfsdf </p> <script src="https://cdn.bootcss.com/jquery/1.8.3/jquery.js"></script> <script> var count=1; var example = { getData:function () { var data ={ content:'df'+count++, href:'' }; this.renderData(data); }, renderData:function (data) { document.getElementById('point').innerHTML='<p>this is a '+data.content+'点此<a class="read-more" href="javasript:;" rel="external nofollow" rel="external nofollow" >查看更多</a></p>'; $('#point').on('click','.read-more',function () { alert('事故发生点'); }) /* setInterval(function () { console.log('fdfdfg'); },2000);*/ /*用冒泡来绑定事件,类似于Jquery的on绑定事件*/ /* document.querySelector('body').addEventListener('click',function (e) { if(e.target.classList.contains('read-more')){ alert('事故发生点'); } })*/ } } ; document.querySelector('.add_but').addEventListener('click',function (e) { example.getData(); e.stopImmediatePropagation(); }); </script> </body> </html>
example.getData() is triggered. After simulating ajax to obtain the data successfully, the content of the element class named point in the page will be refreshed locally, and at the same time, this function will be loaded. The read-more A tag in the content is bound to an event, and the effect we want appears. When the element is loaded for the first time, the page is normal, and the 'accident point' pops up once. When the second refresh is triggered, you You will find that it pops up twice, and the third time, you will find that it pops up three times, and so on. . . .
Restore the truth
In fact, the above code is for The code specially written for testing, except for the timer, the other two click events are written in a normal way. Repeated execution will not occur. The normal code:// jquery 事件直接绑定的写法; $('#point .read-more').on('click',function () { alert('事故发生点'); }) // 原生JS 事件直接绑定的写法; document.querySelector('.read-more').addEventListener('click',function (e) { alert('事故发生点'); })
Dom events make sense. For dynamically added elements, events are dynamically bound to this element. After the element is deleted, the corresponding event bound to it will actually be deleted from the event binding queue , rather than the above test code, which gives the impression that after the element is removed, its bound events are still in the memory. But please remember, this is a misunderstanding. The code tested above gives this illusion because we do not bind events to dynamically added elements, but only use the form of event delegation. , in fact, the event is bound to the #point element, which always exists. Event bubbling is used to let the program know that we clicked on the dynamically added link element. In the test, native js was specially used to reproduce the event delegation. The principle of jquery's on binding event is basically the same.
document.querySelector('body').addEventListener('click',function (e) { if(e.target.classList.contains('read-more')){ alert('事故发生点'); } })
Those methods to eliminate bugs
Timer
This is the most common mistake The error is of course the easiest to solve, because when setting the timer, it will return a value. This value should be a number in the timer in the event queue, similar to 9527; the step is to set a global variable to Keep this return value id, and every time you set the timer, first clear the timer that has been set by idclearInterval(intervalId); //粗暴的写法 intervalId&&clearInterval(intervalId); //严谨的写法 intervalId=setInterval(function () { console.log('fdfdfg'); },2000);
Dom event
In fact, we above As mentioned before, the most direct way is not to use event delegation, but to use direct binding; if you really want to use event delegation to bind events, then unbind. The unbind function is provided in jquery to unbind events. However, after jquery version 1.8, this method is no longer recommended, and the off method is recommended. For example, in the on event delegation method above, to unbind, you can use the statement$('#point').off('click','.read-more').
有缺陷的解决方案,添加flag
很好理解,第一次绑定后,flag置位,下一次在执行这个绑定时,程序就知道在这个节点上已经有了绑定,无需再添加,具体操作就是:
var flag = false; var example = { getData: function () { var data = { content: 'df' + count++, href: '' }; this.renderData(data); }, renderData: function (data) { document.getElementById('point').innerHTML = '<p>this is a ' + data.content + '点此<a class="read-more" href="javasript:;" rel="external nofollow" rel="external nofollow" >查看更多</a></p>'; !flag && $('#point').on('click', '.read-more', function () { alert('事故发生点'+data.content); }); flag = true; } };
从逻辑上,看起来没有问题,但仔细观察,发现这是有问题的。当我们第二次,第三次刷新时,弹出框的内容还是和第一次模拟刷新后点击后弹出的内容一致,还是'事故发生点df1',而非和内容一样递增,为什么呢,感觉事件队列里面的回调函数被单独保存起来了,data被深拷贝了,而不再是一个引用。确实有点难理解,我也不知道到底是为什么,如果哪位能说清楚,还请一定告知。
结个尾写在最后,其实平常写一些程序时,事件绑定,造成程序重复执行这些情况很少发生,其通常会出现在我们写插件的时候,插件需要适应多种调用环境,所以在插件内部做到防止事件重复绑定的情况非常重要。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of How to add elements dynamically in JS. 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



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

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

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

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

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

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

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file
