jquery 给动态生成的标签绑定事件的几种方

jquery 给动态生成的标签绑定事件的几种方,第1张

1、动态绑定事件

<div id=box></div>

<button id=btn>动态生成标签</button>

<script>

window.onload=function(){

   document.getElementById("btn").onclick=function(){

      var span=document.createElement("span")

      span.innerHTML="点我"+Math.random()

      span.onclick=function(){

         alert(this.innerHTML)

      }

      document.getElementById("box").appendChild(span)

   }

}

</script>

2、事件委托:

<div id=box></div>

<button id=btn>动态生成标签</button>

<script>

window.onload=function(){

   document.getElementById("box").onclick=function(e){

      var e=e||window.event

      if(e.target!=e.currentTarget){

         alert(e.target.innerHTML)

      }

   }

   document.getElementById("btn").onclick=function(){

      var span=document.createElement("span")

      span.innerHTML="点我"+Math.random()

      document.getElementById("box").appendChild(span)

   }

}

</script>

可以通过事件代理方式加载事件,比如你的父容器是ul,ul下面的li是动态生成的,绑定点击事件可以这样写:

$('ul').on('click','li',function(){//code here})


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11835000.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-19
下一篇2023-05-19

发表评论

登录后才能评论

评论列表(0条)

    保存