ash-sky

jq为动态创建的元素绑定事件

jquery中的on()为新添加的动态元素绑定事件

html代码:

<div>
  <p>弹出</p>
  <button>添加元素</button>
</div>

jq代码:

$("button").click(function(){
  $("button").before("<p>"+"新建的"+"</p>")
})
$("div p").each(function(){                         //点击按钮生成的元素p,无法绑定事件:alert(”123“)
  $(this).on("click",function(){            
    alert("123")
  })
})
$("div p").each(function(){                         //点击按钮生成的元素,依然可以绑定事件:alert("123")
  $(this).parent().on("click","p",function(){              //.on前面是元素p的父级,第二个参数,是绑定事件对象。
    alert("123")
  })
})

 希望对大家有帮助,live高版本移出了!建议大家不要用了!

发表于 2018-09-10 17:03  ash-sky  阅读(2408)  评论(0编辑  收藏  举报
 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-05-19
  • 2021-10-19
  • 2021-10-19
  • 2021-10-19
  • 2021-10-19
  • 2021-06-13
猜你喜欢
  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
  • 2021-08-28
  • 2021-10-23
  • 2021-09-18
  • 2022-12-23
相关资源
相似解决方案