1. 程式人生 > >動態繫結事件

動態繫結事件

<head>
	<meta charset="UTF-8">
	<title>demo</title>
	<script type="text/javascript" src="js/jquery-1.10.2/jquery.min.js"></script>
</head>

<body>
	<button id="btn">新增html</button>
	<div style="width: 100px;height: 100px;background-color: yellow;" id="div"></div>
	<script type="text/javascript">
		$(function() {
			//正確的方式
			$("#div").on("click", ".demo", function() {
				alert("ok");
			});
			//錯誤的方式
			/*$("#div .demo").on("click", function() {
				alert("ok");
			});*/
			$("#btn").click(function() {
				var html = '<div class="demo" style="width: 100px;height: 100px;background-color: greenyellow;" ></div>';
				$("#div").html(html);
			});
		});
	</script>
</body>

on()方法替代了bind(), live() 和 delegate() 方法。on()方法可以給當前元素和未來元素繫結事件。

childSelector項是可選的,如果沒有childSelector項的話,只能給被選元素(已存在的元素)繫結事件,不能給未來元素 點選新增html然後點選div彈出alert,說明方法正確執行:在這裡插入圖片描述