当前位置:网站首页>完善的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
边栏推荐
- 力扣刷题日记/day6/6.28
- Android uses sqliteopenhelper to flash back
- Is it safe to open an account online? is that true?
- Li Kou brush question diary /day7/6.30
- 力扣刷题日记/day1/2022.6.23
- Li Kou brush question diary /day4/6.26
- Neglected problem: test environment configuration management
- 一种将Tree-LSTM的强化学习用于连接顺序选择的方法
- 力扣刷题日记/day7/6.30
- .NET ORM框架HiSql实战-第二章-使用Hisql实现菜单管理(增删改查)
猜你喜欢

The controversial line of energy replenishment: will fast charging lead to reunification?

TorchDrug教程

How is the entered query SQL statement executed?

Neglected problem: test environment configuration management

Why are some online concerts always weird?

爬虫(6) - 网页数据解析(2) | BeautifulSoup4在爬虫中的使用

ByteDance dev better technology salon was successfully held, and we joined hands with Huatai to share our experience in improving the efficiency of web research and development

能源行业的数字化“新”运维

Is it science or metaphysics to rename a listed company?

Li Kou brush question diary /day7/2022.6.29
随机推荐
Reptile elementary learning
ISO27001 certification process and 2022 subsidy policy summary
一直以为做报表只能用EXCEL和PPT,直到我看到了这套模板(附模板)
Numpy 的仿制 2
TorchDrug教程
[system disk back to U disk] record the operation of system disk back to U disk
How to improve development quality
【2022年江西省研究生数学建模】水汽过饱和的核化除霾 思路分析及代码实现
项目通用环境使用说明
[210] usage of PHP delimiter
Scala基础教程--17--集合
The block:usdd has strong growth momentum
网上开户安全吗?是真的吗?
6.26CF模拟赛B:数组缩减题解
People in the workplace with a miserable expression
Lua emmylua annotation details
What types of Thawte wildcard SSL certificates provide
vbs或vbe如何修改图标
Is it science or metaphysics to rename a listed company?
Crawler (6) - Web page data parsing (2) | the use of beautifulsoup4 in Crawlers