jQuery学习笔记之给动态生成元素绑定事件

时间:2021-07-16 01:13:23

使用jQuery的$(selector).on("event","child",function(){});给静态元素绑定事件是比较容易的,比如下面这行代码就是给 p 元素绑定点击事件

$("p").on("click", function () {
alert("you click the p element");
})

但是如果是动态生成的元素,使用上面这段代码是没有效果的,因此要选择动态元素的某个父级静态元素,以此来绑定事件方可,具体见下段代码。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<script>
$(document).ready(
function () {
$("button").on("click", function () {
$("#myDiv").append("<p>this is a new paragraph!</p>");
});
$(document).on("click", "#myDiv p", function () {
alert("you clicked the p element!");
})
}
)
</script>
<body>
<div>
<button id="btn_add">点击动态增加元素</button>
</div>
<div id="myDiv"></div>
</body>
</html>

别的没什么说的,要注意的是各种绑定事件要写在$(doucument).ready() 中,否则无效。