事件代理: 网页设计中一种设计思想 利用事件对象中引用的目标对象这个技术来实现的
无论事件触发时 是不是目标对象的监听器 在监听器内部的事件对象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>
<button onclick="load1()">网络请求了新的新闻</button>
先看看html的解构 可以看出来box1里面嵌套了四个box2元素
现在我们的要求是去点击这几个box2盒子点什么打印什么
var box2s=document.querySelectorAll(".box2")
box2s.forEach(el=>{
el.addEventListener("click",function(e){
console.log(this.innerHTML)
})
})
先获取到所有box2元素,然后使用foreach遍历到所有的box2,然后绑定点击事件
这样会有两个问题:
1,这样是静态的方法,如果我们后面继续再box1添加几个子元素,那么这几个子元素则不会获得新的点击事件
2,性能消耗更高 业务却相同
如果我们采用事件代理
var box1=document.querySelector(".box1")
box1.addEventListener("click",function(e){
console.log(e.target.innerHTML)
})
使用了事件对象的target属性,target属性就表示点击的是哪一个事件对象,而且事件是绑定在父元素上的,子元素也会获得这个事件
var box1=document.querySelector(".box1")
box1.addEventListener("click",function(e){
console.log(e.target)//事件的目标对象
console.log(e.srcElement)//事件的目标对象
console.log(document.documentElement)//html元素
console.log(document.body)//body元素
console.log(document)//根节点
})
console.log(box5.dataset)
了解这几个元素