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高版本移出了!建议大家不要用了!

原文地址:https://www.cnblogs.com/ash-sky/p/9620815.html