This time I will bring you a detailed explanation of the steps to add events to dynamically created elements with JS. What are the precautions for adding events to dynamically created elements with JS. Here are practical cases, let’s take a look.
We all know how to add events to elements directly generated in html, but how to add events to a dynamically generated element? The live
method in jquery can do this
The specific implementation can be seen in the demo
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JS实现为动态创建的元素添加事件</title> <script src="js/lib/jquery-1.7.2.min.js"></script> </head> <body> <button id="btn">添加事件</button> <p id="panel"></p> <script> // js原生实现 // var btn=document.getElementById("btn"); // btn.onclick=function(){ // var arr= []; // for(var i=0;i<10;i++){ // arr.push("<p id='nep'>"+i+"</p>"); // } // // document.getElementById("panel").innerHTML=arr.join('<br/>'); // } // //jquery部分实现 $("#btn").click(function(){ var arr= []; for(var i=0;i<10;i++){ arr.push("<p id='nep'>"+i+"</p>"); } $("#panel").html(function(){ return arr.join("<br/>"); }); }); //为动态创建的html标签元素添加事件 $("#nep").live("click",function(){ var that=$(this);//获取当前点击的this对象 console.log(that.text()); }); </script> </body> </html>
Running results:
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:
Summary of js data parsing skills
##Tips on using DOM event binding in js
The above is the detailed content of Detailed explanation of the steps to add events to dynamically created elements using JS. For more information, please follow other related articles on the PHP Chinese website!