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:
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:
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!