示例工程 19-dom-events

19-dom-events/02-delegation/index.html

html · 1.2 KB

运行:19 · 事件委托

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>19 · 事件委托</title>
</head>
<body>
  <ul id="list">
    <li>alpha <button data-id="alpha">删除</button></li>
    <li>beta <button data-id="beta">删除</button></li>
    <li>gamma <button data-id="gamma">删除</button></li>
  </ul>
  <p id="log"></p>
 
  <script type="module">
    import { run } from './main.js';
 
    const list = document.getElementById('list');
    const removed = [];
    let handlerCalls = 0;
 
    // 只挂一个监听器:事件委托
    list.addEventListener('click', (event) => {
      handlerCalls += 1;
      const button = event.target.closest('button[data-id]');
      if (!button) return;
      removed.push(button.dataset.id);
      button.closest('li').remove();
    });
 
    // 模拟点击第一项,验证委托生效
    list.querySelector('button[data-id]').click();
    document.getElementById('log').textContent = `removed=${removed.join(',')} calls=${handlerCalls}`;
    console.log('removed =>', JSON.stringify(removed));
    console.log('handlerCalls =>', handlerCalls);
    console.log('remaining li =>', list.children.length);
    run();
  </script>
</body>
</html>