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