跳到正文
Skillpedia
网站与界面(前端)75k · #2837

event-delegation

它能做什么

这项技能检查为列表项或表格行附加大量事件监听器的代码。适用于构建列表和动态页面的开发者。

适用场景

  • ✓当你给长列表中的每个项目都添加了相同的点击处理程序的时候。
  • ✓当之后新增的列表项对点击没有反应的时候。
  • ✓当一个带有大量监听器的页面占用了过多内存的时候。

技能链接

https://github.com/thedaviddias/Front-End-Checklist/blob/main/skills/event-delegation/SKILL.md

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/thedaviddias/Front-End-Checklist/blob/main/skills/event-delegation/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 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.

repo: thedaviddias/Front-End-Checklist

热度

GitHub 星标
75k
排名
#2837
许可证
MIT
更新时间
2026/10/31

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能