当前位置:网站首页>完善的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 /day5/2022.6.27
- Thawte通配符SSL证书提供的类型有哪些
- Redis master-slave replication
- Five thousand words to clarify team self-organization construction | Liga wonderful talk
- 网上开户安全吗?是真的吗?
- Scala基础教程--17--集合
- How to improve development quality
- What if the self incrementing ID of online MySQL is exhausted?
- MXNet对GoogLeNet的实现(并行连结网络)
- 李迟2022年6月工作生活总结
猜你喜欢
Scala基础教程--20--Akka
Li Kou brush question diary /day7/2022.6.29
Unity makes revolving door, sliding door, cabinet door drawer, click the effect of automatic door opening and closing, and automatically play the sound effect (with editor extension code)
基于unity的愤怒的小鸟设计
一、C语言入门基础
Just today, four experts from HSBC gathered to discuss the problems of bank core system transformation, migration and reconstruction
被忽视的问题:测试环境配置管理
Microservice architecture debate between radical technologists vs Project conservatives
ISO27001认证办理流程及2022年补贴政策汇总
力扣刷题日记/day7/6.30
随机推荐
Installation and use of VMware Tools and open VM tools: solve the problems of incomplete screen and unable to transfer files of virtual machines
[mathematical modeling of graduate students in Jiangxi Province in 2022] analysis and code implementation of haze removal by nucleation of water vapor supersaturation
【209】go语言的学习思想
Li Kou brush question diary /day4/6.26
爬虫(6) - 网页数据解析(2) | BeautifulSoup4在爬虫中的使用
Scala基础教程--17--集合
Once the "king of color TV", he sold pork before delisting
Wanghongru research group of Institute of genomics, Chinese Academy of Agricultural Sciences is cordially invited to join
蓝桥:合根植物
学习路之PHP--phpstudy创建项目时“hosts文件不存在或被阻止打开”
【2022年江西省研究生数学建模】冰壶运动 思路分析及代码实现
Li Kou brush question diary /day5/2022.6.27
Li Kou brush question diary /day1/2022.6.23
一、C语言入门基础
Just today, four experts from HSBC gathered to discuss the problems of bank core system transformation, migration and reconstruction
一直以为做报表只能用EXCEL和PPT,直到我看到了这套模板(附模板)
6.26CF模拟赛E:价格最大化题解
Li Kou brush question diary /day2/2022.6.24
Scala基础教程--18--集合(二)
Summary of subsidy policies across the country for dcmm certification in 2022