当前位置:网站首页>完善的js事件委托
完善的js事件委托
2022-07-04 17:07:00 【欲饮琵琶码上催】
function eventDelegate(element, eventType, selector, fn) {
element.addEventListener(eventType, e => {
let el = e.target;
// 当点击的元素不为li本⾝的时候,⽐如说span,就找⽗级是否为li
while (!el.matches(selector)) {
// 不断向上找⽗级元素,判断是否有li标签
if (element === el) {
// 直到找到代理元素就不执⾏委托
el = null;
break;
}
el = el.parentNode;
}
el && fn.call(el, e, el);
})
return element;
}
eventDelegate(ul, 'click', 'li', function (e, el) {
console.log(`点击了${
this}标签`)
})
ul.addEventListener('click', function() {
let el = e.target
while (el && !el.matches(selector)) {
el = el.parentNode
if (element === el) {
el = null
}
}
if (el) {
console.log('执行回调函数')
}
}
参考文章
https://zhuanlan.zhihu.com/p/26986963
边栏推荐
- Li Kou brush question diary /day4/6.26
- Wireshark抓包TLS协议栏显示版本不一致问题
- MySQL常用增删改查操作(CRUD)
- 【211】go 处理excel的库的详细文档
- Weima, which is going to be listed, still can't give Baidu confidence
- Redis master-slave replication
- Is it safe to download the mobile version of Anxin securities and open an account online
- VMware Tools和open-vm-tools的安装与使用:解决虚拟机不全屏和无法传输文件的问题
- Open source PostgreSQL extension age for graph database was announced as the top-level project of Apache Software Foundation
- What if the self incrementing ID of online MySQL is exhausted?
猜你喜欢

I always thought that excel and PPT could only be used for making statements until I saw this set of templates (attached)

如何提高开发质量

Li Kou brush question diary /day5/2022.6.27

力扣刷题日记/day6/6.28

Reptile elementary learning

Blue bridge: sympodial plant

一种将Tree-LSTM的强化学习用于连接顺序选择的方法

线上MySQL的自增id用尽怎么办?

Load test practice of pingcode performance test

Scala基础教程--15--递归
随机推荐
Neglected problem: test environment configuration management
Interpretation of SIGMOD '22 hiengine paper
Scala基础教程--12--读写数据
Russia arena data releases PostgreSQL based products
[210] usage of PHP delimiter
MXNet对GoogLeNet的实现(并行连结网络)
The money circle boss, who is richer than Li Ka Shing, has just bought a building in Saudi Arabia
2022年全国CMMI认证补贴政策|昌旭咨询
Load test practice of pingcode performance test
Journal des problèmes de brosse à boutons de force / day6 / 6.28
Wanghongru research group of Institute of genomics, Chinese Academy of Agricultural Sciences is cordially invited to join
I always thought that excel and PPT could only be used for making statements until I saw this set of templates (attached)
TorchDrug教程
TCP两次挥手,你见过吗?那四次握手呢?
力扣刷题日记/day1/2022.6.23
1、 Introduction to C language
SIGMOD’22 HiEngine论文解读
NBA赛事直播超清画质背后:阿里云视频云「窄带高清2.0」技术深度解读
Detailed explanation of the maturity classification of ITSS operation and maintenance capability | one article clarifies the ITSS certificate
Scala基础教程--18--集合(二)