event-delegation
它能做什么
这项技能检查为列表项或表格行附加大量事件监听器的代码。适用于构建列表和动态页面的开发者。
适用场景
- ✓当你给长列表中的每个项目都添加了相同的点击处理程序的时候。
- ✓当之后新增的列表项对点击没有反应的时候。
- ✓当一个带有大量监听器的页面占用了过多内存的时候。
技能链接
https://github.com/thedaviddias/Front-End-Checklist/blob/main/skills/event-delegation/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“请简化我这个列表的点击处理程序,使新增的项目也能正常工作。”
每周 5 个新技能,1 分钟读完。
工作原理
智能体会找出附加在许多子元素上的相同处理程序,并建议在它们的父元素上只设置一个监听器。它使用 closest 来确定被点击的项目。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Use event delegation for dynamic content
Adding hundreds of individual event listeners for list items or table rows consumes significant memory and creates performance overhead. Dynamic content (items loaded via AJAX or rendered after user actions) won't have event listeners unless you re-attach them after each update — event delegation solves both problems at once.
Quick Reference
- Attach one listener to a parent instead of many to individual children
- Use event.target.closest() to identify the intended target element
- Event delegation automatically works for elements added dynamically
- Clean up listeners on the parent when the container is removed
Check
Find any code in this file that attaches the same event handler to multiple elements in a loop. Suggest event delegation as an alternative.
Fix
Refactor these per-element event listeners to use event delegation on the common parent container.
Explain
Explain event delegation, how event bubbling enables it, and when to use closest() vs target.
Code Review
Review scripts, client components, and browser execution paths related to Use event delegation for dynamic content. Flag exact imports, event handlers, runtime side effects, or blocking operations that violate the rule, and state how the change should be verified in the browser.
For full implementation details, code examples, and framework-specific guidance,
see references/rule.md.
Rule page: https://frontendchecklist.io/rules/javascript/event-delegation
常见问题
什么是事件委托?
它是指在共享的父元素上监听事件,并检查是哪个子元素触发的,而不是在每个子元素上分别监听。
为什么它对新增内容有帮助?
父元素的监听器可以捕获来自任何子元素的事件,包括页面加载后新增的项目。
closest 有什么用?
这项技能使用 closest 来找到目标元素,即使点击落在其内部的某个元素上也可以。
详情
作者的原始描述
Use when reviewing scripts, client components, bundles, or runtime behavior related to Use event delegation for dynamic content. Inspect both source code and the browser execution path so fixes target the real bottleneck or bug.
热度
- GitHub 星标
- 75k
- 排名
- #2837
- 许可证
- MIT
- 更新时间
- 2026/10/31
评论
- …
同一仓库的更多技能
frontendchecklist
75k使用命令行工具,依据 380 多条关于无障碍、速度、SEO 和安全的规则,检查前端代码和线上页面。
frontend-checklist-global
75k依据全部 386 条 Front-End Checklist 规则审查前端项目,并为发现的每个问题给出具体修复方法。
404-page
75k检查你的页面缺失提示是否提供有用的链接,并返回真正的 404 状态,帮助迷路的访客找到方向。
about-page
75k审查你的网站是否有清晰的关于页面,说明由谁运营,以建立访客和搜索引擎的信任。