Home Web Front-end JS Tutorial How to add elements dynamically in JS

How to add elements dynamically in JS

Jun 22, 2018 pm 01:55 PM
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事件绑定')
 });
Copy after login

Second type:

 document.addEventListener('click',function (e) {
 consol.log('原生事件绑定')  
 });
Copy after login

Third type:

 var id = setInterval(function () {
 console.log('定时器循环事件绑定')
 },1000);
Copy after login

I believe many allies write the code above every day Well, seemingly simple event binding can often bring us unexpected results, especially in this era where SPA and AJAX page partial refresh are so popular.

So what is event binding, and what causes repeated execution of programs? It seems that this matter is not that simple to clear, so let’s use a test code to illustrate it. You can copy it locally and try it yourself:

<!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:&#39;df&#39;+count++,
  href:&#39;&#39;
  };
  this.renderData(data);
 },
 renderData:function (data) {
  document.getElementById(&#39;point&#39;).innerHTML=&#39;<p>this is a &#39;+data.content+&#39;点此<a class="read-more" href="javasript:;" rel="external nofollow" rel="external nofollow" >查看更多</a></p>&#39;;
  $(&#39;#point&#39;).on(&#39;click&#39;,&#39;.read-more&#39;,function () {
  alert(&#39;事故发生点&#39;);
 })
/*  setInterval(function () {
  console.log(&#39;fdfdfg&#39;);
  },2000);*/
  /*用冒泡来绑定事件,类似于Jquery的on绑定事件*/
 /* document.querySelector(&#39;body&#39;).addEventListener(&#39;click&#39;,function (e) {
  if(e.target.classList.contains(&#39;read-more&#39;)){
   alert(&#39;事故发生点&#39;);
  }
  })*/

 }
 } ;
 document.querySelector(&#39;.add_but&#39;).addEventListener(&#39;click&#39;,function (e) {
 example.getData();
 e.stopImmediatePropagation();
 });
</script>
</body>
</html>
Copy after login

The above is a test code I wrote to clarify this matter. You can copy it and try it. When we click the button on the page, the function

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. . . .

OMG, what’s wrong with this program? I clearly know that before each event is bound, the previously bound elements are deleted. Why, the deleted corpse feels like it is still moving. Well, the above is my first An exclamation made when encountering this situation.

Finally, I asked the master around me, and I suddenly realized that the binding was always there, and this binding was saved in a place called the event queue. He was not in the main thread of loop execution, and drew a A picture that requires tacit understanding to be understood, so I reluctantly took a look at it.

Event queue

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 事件直接绑定的写法;
 $(&#39;#point .read-more&#39;).on(&#39;click&#39;,function () {
  alert(&#39;事故发生点&#39;);
 })
 // 原生JS 事件直接绑定的写法;
 document.querySelector(&#39;.read-more&#39;).addEventListener(&#39;click&#39;,function (e) {
  alert(&#39;事故发生点&#39;);
 })
Copy after login

Do you see the difference? In fact That is, there is no need to bubble up event delegation, but directly bind events to the added elements. So

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(&#39;body&#39;).addEventListener(&#39;click&#39;,function (e) {
 if(e.target.classList.contains(&#39;read-more&#39;)){
  alert(&#39;事故发生点&#39;);
 }
})
Copy after login

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 id

 clearInterval(intervalId); //粗暴的写法
 intervalId&&clearInterval(intervalId); //严谨的写法
 intervalId=setInterval(function () {
  console.log(&#39;fdfdfg&#39;);
  },2000);
Copy after login

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: &#39;df&#39; + count++,
  href: &#39;&#39;
  };
  this.renderData(data);
 },
 renderData: function (data) {
  document.getElementById(&#39;point&#39;).innerHTML = &#39;<p>this is a &#39; + data.content + &#39;点此<a class="read-more" href="javasript:;" rel="external nofollow" rel="external nofollow" >查看更多</a></p>&#39;;
  !flag && $(&#39;#point&#39;).on(&#39;click&#39;, &#39;.read-more&#39;, function () {
  alert(&#39;事故发生点&#39;+data.content);
  });
  flag = true;
 }
 };
Copy after login

从逻辑上,看起来没有问题,但仔细观察,发现这是有问题的。当我们第二次,第三次刷新时,弹出框的内容还是和第一次模拟刷新后点击后弹出的内容一致,还是'事故发生点df1',而非和内容一样递增,为什么呢,感觉事件队列里面的回调函数被单独保存起来了,data被深拷贝了,而不再是一个引用。确实有点难理解,我也不知道到底是为什么,如果哪位能说清楚,还请一定告知。

结个尾写在最后,其实平常写一些程序时,事件绑定,造成程序重复执行这些情况很少发生,其通常会出现在我们写插件的时候,插件需要适应多种调用环境,所以在插件内部做到防止事件重复绑定的情况非常重要。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用node.js如何创建子进程(详细教程)

使用ES6如何实现单例模式

如何把Angular项目部署到nginx上

在vue中使用v-model如何实现父子组件通信

在react中有关组件通信有哪些方法?

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!

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)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

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

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

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 create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

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 with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

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

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

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 map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

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

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

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 How to use JS and Baidu Maps to implement map polygon drawing function Nov 21, 2023 am 10:53 AM

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

See all articles