为动态添加的元素绑定事件处理函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../common/jquery-1.8.3.min.js"></script>
</head>
<body>
<button>为动态添加的的元素绑定事件处理函数</button>
<p>Click me to create new paragrph!</p>
<div id="allMsg">
</div>
</body>
<script>
$(function(){
$("button:eq(0)").click(function(){
console.log("1111");
$("p").live("click",function(){
$(this).after("<p>这是动态添加的</p>")
})
})
$("#btn").live('click',function(){
alert("111");
})
// $("#btn").click(function(){
// alert("111");
// })
var str = '';
for(var i=0;i<10;i++){
str += '<p>模拟数据</p>';
}
str += '<button id="btn">动态添加按钮,添加点击事件</button>';
$("#allMsg").append(str);
})
</script>
</html>
live():函数为被选中元素附加一个或多个事件处理程序,并规定当这些事件发生时运行的函数,适用于匹配选择器的当前及未来的元素(比如脚本创建的新元素)

浙公网安备 33010602011771号