当前位置:网站首页>dom——事件代理
dom——事件代理
2022-07-22 00:25:00 【ca11meback】
事件代理: 网页设计中一种设计思想 利用事件对象中引用的目标对象这个技术来实现的
无论事件触发时 是不是目标对象的监听器 在监听器内部的事件对象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)
了解这几个元素
边栏推荐
- ABAP grammar foundation 2
- Interview 3 (multiple processes call the same dynamic library)
- How to add a map to a page
- 软件测试禅道是什么?如何使用?
- ABAP grammar basics 3
- Pytorch (IV) -- pytorch model definition
- AQS of concurrent memory model -- reentrantlock locking process
- Set lazy loading and default tick for El tree
- 异常检测 and 自编码器(2)
- Machine learning - Integrated Learning
猜你喜欢
并发内存模型之AQS——ReentrantLock加锁流程
MySQL grant之后一定要跟随flush privileges么?
Looking for Fibonacci number
Multithreading and high concurrency -- synchronized locking and unlocking process
通讯录(文件版本)
美团二面: Redis 5 种基础数据结构?
I met a 38K from Tencent two days ago, which showed me the ceiling of the foundation. Today I give it to you~
全链路压测:影子库与影子表之争
C language: leak detection and filling (II)
【Flutter组件】Expanded详解
随机推荐
AQS of concurrent memory model -- reentrantlock locking process
mysql php 导入数据出错
香港云服务器和物理服务器哪个更容易宕机?
Prometheus 2.37.0 new features
ABAP语法基础2
C language hierarchical understanding (C language branches and circular statements)
How to add a map to a page
Shengxin often draws analytical graphics -- various types of heat maps! Have you learned?
【Flutter组件】Expanded详解
Address book (file version)
MySQL高级篇(C)
Notes and Thoughts on the red dust of the curtain of Heaven (II) you know what others know and what you know
多线程与高并发—— Synchronized 加锁解锁流程
微服务架构 | 服务注册发现中心/配置中心/消息总线 - [nacos] TBC...
The undeclared identifier "MainWindow" is used in the QT code of Kirin system“
PyTorch(四)——PyTorch模型定义
ABAP grammar foundation 4
Pytorch(三)——FashionMNIST时装分类
ABAP grammar basics 3
51单片机外设篇:LED点阵