事件代理: 网页设计中一种设计思想 利用事件对象中引用目标对象(event.target)这个技术来实现的
无论事件触发时是不是目标对象的监听器 在监听器内部的事件对象event中都可以访问这个事件的目标对象,利用这个特点去绑定事件给父级元素 来代理子级元素的业务,这种设计就是事件代理。
在未学习事件代理时,我们要获得一个父元素下的所以子元素的内容,是每一个子元素都绑定事件监听,如:
<style>
.box1{
background-color: darkgray;
}
.box2{
width: 120px;
height: 40px;
background-color: firebrick;
margin: 10px;
}
</style>
<div class="box1">
<div class="box2">hello1</div>
<div class="box2">hello2</div>
<div class="box2">hello3</div>
<div class="box2">hello4</div>
</div>
<script>
var box2s=document.querySelectorAll(".box2")
box2s.forEach(el=>{
el.addEventListener("click",function(e){
console.log(this.innerHTML)
})
})
</script>
现在的效果是点击对应的box2打印对于的内容。
这样设计有两个缺点
1.静态的事件绑定:如果动态的添加元素进去 添加进去的元素没有这个事件
2.性能消耗更高 业务却相同
在学习了事件代理之后,我们就可以简化设计,只用给box绑定事件,解决上述缺点。
改进代码:
<style>
.box1{
background-color: darkgray;
}
.box2{
width: 120px;
height: 40px;
background-color: firebrick;
margin: 10px;
}
</style>
<div class="box1">
<div class="box2">hello1</div>
<div class="box2">hello2</div>
<div class="box2">hello3</div>
<div class="box2">hello4</div>
</div>
<script>
var box1=document.querySelector(".box1")
box1.addEventListener("click",function(e){
console.log(e.target.innerHTML)
})
</script>
补充知识点:
获取目标对象除了事件对象点target外,还可以用事件对象点srcElement来获取目标对象;
document.documentElement获取html元素;
document.body获取body元素;
document为根节点