← 中文资源

简体中文版本

event.target 与 currentTarget 的分工

冒泡过程中 target 始终是最初被点中的元素,currentTarget 是当前正在执行监听器的元素:父容器只绑一次监听,靠 target 加 closest 完成委托分派,currentTarget 则随冒泡层级变化。

阅读英文原文

实现说明

toolbar 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 浏览器才是这里的运行环境:document 在 Node 里拿不到。
  • 直接运行文件,输出会带上标签,比如 clicked:、listener on:、action:——输出的每一行都能指回产生它的那次调用。

常见问题

「event.target 与 currentTarget 的分工」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

核心语句

const toolbar = document.querySelector('#toolbar');

代码示例

// one container plus several buttons: the listener is bound to the container only
const toolbar = document.querySelector('#toolbar');

toolbar.addEventListener('click', (event) => {
  // target: the element actually clicked (the button, or the parent of a text node inside it)
  console.log('clicked:', event.target.tagName, event.target.dataset.action);
  // currentTarget: the element currently running this listener, always toolbar
  console.log('listener on:', event.currentTarget.id);
  // delegation: walk up from target to the nearest button, then dispatch the action
  const button = event.target.closest('button');
  if (button) console.log('action:', button.dataset.action);
});

// every level the event bubbles through runs the listener: target stays fixed while currentTarget changes per level