jquery live()函数原理
- 将事件绑定到父节点,由于事件冒泡,所有事件最终会冒泡到document节点
- 当有事件触发时,则判断事件类型和触发事件的元素是否一致,如果相同则执行函数
实例
<!doctype html>
<html>
<head>
<title>jquery live()函数原理及实现</title>
<style type="text/css">
table{
border-collapse:collapse;
border-spacing:0;
}
td{
border:1px solid #cdcdcd;
}
</style>
<script type="text/javascript">
function live(target, type, fn){
document.onclick = function(event){
var e = event ? event : window.event;
addRow();
if(e.type == type && e.target.tagName.toLocaleLowerCase() == target){
fn();
}
}
}
function addRow(){
var x=document.getElementById("tb").insertRow(0);
var y=x.insertCell(0);
var z=x.insertCell(1);
y.innerHTML="NEW CELL1";
z.innerHTML="NEW CELL2";
}
live("td", "click", function(){
alert("live");
});
</script>
</head>
<body>
<table id="tb">
<tr>
<td>..........................................</td>
<td>..........................................</td>
</tr>
<tr>
<td>..........................................</td>
<td>..........................................</td>
</tr>
<tr>
<td>..........................................</td>
<td>..........................................</td>
</tr>
</table>
</body>
</html>
参考
jquery live()函数原理及实现