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

JS implementation example of adding event operations to dynamically created elements

亚连
Release: 2018-05-29 16:22:28
Original
1756 people have browsed it

This article mainly introduces the JS implementation of adding event operations to dynamically created elements, involving the dynamic addition of javascript page elements and event response related operation skills. Friends in need can refer to the following

The examples in this article describe JS Implement event operations for dynamically created elements. Share it with everyone for your reference, the details are as follows: We all know how to add events to elements directly generated in

html, but how to add events to a dynamically generated element, live# in jquery ##Methods can do this

The specific implementation can be seen in the demo

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>www.jb51.net - 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=&#39;nep&#39;>"+i+"</p>");
//       }
//
//     document.getElementById("panel").innerHTML=arr.join(&#39;<br/>&#39;);
//     }
//
      //jquery部分实现
      $("#btn").click(function(){
        var arr= [];
        for(var i=0;i<10;i++){
          arr.push("<p id=&#39;nep&#39;>"+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>
Copy after login

Running results:

The above is me I compiled it for everyone, I hope it will be helpful to everyone in the future.

Related articles:

Introduction to the calling sequence of functions in vue

##Detailed explanation of dynamic components and render based on vue2.0

Vue’s method of dynamically creating and deleting data

The above is the detailed content of JS implementation example of adding event operations to dynamically created elements. For more information, please follow other related articles on the PHP Chinese website!

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