事件代理:利用事件冒泡的特性,将本应该注册在子元素上的处理事件注册在父元素上,这样点击子元素时本身没有相应事件就到父元素上做出响应的反应。
先看一个没有做代理的例子
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<style>
*{
padding:0;
margin:0;
}
li{
list-style:none;
float:left;
width:50px;
height:30px;
background:powderblue;
margin:20px;
text-align:center;
}
</style>
</head>
<body>
<ul id='container'>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</body>
<script>
var ls = document.getElementsByTagName("li");
for(var i=0;i<ls.length;i++){
ls[i].onmouseover=function(){
this.style.backgroundColor='red';
}
ls[i].onmouseout=function(){
this.style.backgroundColor='powderblue';
}
}
//3秒后创建一个新的li
setTimeout(function(){
var newLi = document.createElement("li");
newLi.innerText='6';
document.getElementById("container").appendChild(newLi);
},3000)
</script>
</html>
鼠标移入会变颜色,鼠标移出会恢复原来的颜色
最后这个6 是用setTimeout新创立的,除非我们再次给这个li指定onmouseover、onmouseout事件,否则鼠标移入移出是没有反应的,如果用事件代理就能完美避免这个问题。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<style>
*{
padding:0;
margin:0;
}
li{
list-style:none;
float:left;
width:50px;
height:30px;
background:powderblue;
margin:20px;
text-align:center;
}
</style>
</head>
<body>
<ul id='container'>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</body>
<script>
var ul = document.getElementById("container");
ul.onmouseover=function(e){
var e = e||window.event;
var target = e.target||e.srcElement;
target.style.backgroundColor='red';
}
ul.onmouseout=function(e){
var e = e||window.event;
var target = e.target||e.srcElement;
target.style.backgroundColor='powderblue';
}
//3秒后创建一个新的li
setTimeout(function(){
var newLi = document.createElement("li");
newLi.innerText='6';
document.getElementById("container").appendChild(newLi);
},3000)
</script>
</html>
再来看看6这个li的鼠标移入移出事件:
无需单独给新增加的li添加事件,因为是他们的父节点UL来处理的,每次新加的节点都是可以生效的。