Home > Web Front-end > JS Tutorial > body text

How to use JS to add events to dynamic elements

php中世界最好的语言
Release: 2018-06-14 14:49:02
Original
1978 people have browsed it

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:




 
 js动态添加事件

 
      
  • 123
  •   
  • 123
  •   
  • 123
  •  
   
Copy after login

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:




 
 www.jb51.net js动态添加事件

 
      
  • 123
  •   
  • 123
  •   
  • 123
  •  
   
Copy after login

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!