index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>事件对象</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript" src="jquery-migrate-1.2.1.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link type="text/css" rel="stylesheet" href="style.css" />
</head>
<body>
<div style="width:200px; height:200px; background:green;" id="box">
<input type="button" class="button" value="按钮" />
<input type="button" class="button" value="按钮" />
<input type="button" class="button" value="按钮" />
</div>
</body>
</html>
demo.js
$(function(){
/*
//.bind() 绑定了三个事件
$('.button').bind('click',function(){
alert('事件不委托!');
});
//使用 live 绑定的是 document ,而非 button
//所以,永远只会绑定一次事件
$('.button').live('click',function(){
alert('事件委托!');
});
//.bind 无法动态绑定事件
$('.button').bind('click',function(){
$(this).clone().appendTo('#box');
});
//.live 可以动态绑定事件,因为事件绑定在 document 上
$('.button').live('click',function(){
$(this).clone().appendTo('#box');
});
//.live 可以动态绑定事件,因为事件绑定在 document 上
$('.button').live('click',function(){
$(this).clone().appendTo('#box');
});
//.live 绑定在 document 上,而点击.button 其实在冒泡到 document 上
//并且点击到 document 时候,需要验证 event.type 和 event.target 才能触发
//.live 是不支持元素连缀的
$('#box').children(0).live('click',function(){
$(this).clone().appendTo('#box');
});
$('.button').live('click',function(){
$(this).clone().appendTo('#box');
});
$('.button').die('click');
$('.button').bind('click',function(){
$(this).clone(true).appendTo('#box');
});
$('.button').live('click',function(){
$('<input type="button" class="button" value="按钮" />').appendTo('#box');
});
*/
//.live 的替代方法 delegate
$('#box').delegate('.button','click',function(){
$(this).clone().appendTo('#box');
});
$('#box').undelegate('.button','click');
//live 语义不清晰,由于他没有指定绑定了谁,所以不清晰
//delegate 语义清晰,绑定谁,谁就在开头
});