双语面试:实现一个事件委托函数

5 阅读1分钟

面试题 Interview Question

实现一个简单的事件委托函数 delegate
Implement a simple event delegation function delegate.

要求 Requirements

  1. 函数接收以下参数:
    The function should accept the following parameters:

    • parent:要绑定事件的父级元素(DOM 元素)
      parent: the parent DOM element to which the event listener is attached
    • selector:需要响应事件的子元素的选择器(字符串)
      selector: a CSS selector string to match target child elements
    • type:事件类型(如 "click"
      type: the type of the event, e.g., "click"
    • handler:当事件发生在符合选择器的子元素上时调用的函数
      handler: the callback function to invoke when an event is triggered on a matching child
  2. 事件处理函数应当只在目标元素或其祖先匹配选择器时触发。
    The event handler should trigger only when the event target or its ancestors match the selector.

参考答案 Reference Solution

function delegate(parent, selector, type, handler) {
  parent.addEventListener(type, function (event) {
    const targetElement = event.target.closest(selector);
    if (targetElement && parent.contains(targetElement)) {
      handler.call(targetElement, event);
    }
  });
}

示例 Example

<ul id="menu">
  <li>首页</li>
  <li>关于</li>
  <li>联系</li>
</ul>
const menu = document.getElementById('menu');

delegate(menu, 'li', 'click', function (event) {
  console.log('你点击了:', this.textContent);
  // You clicked: this.textContent
});

面试考察点 Interview Focus

  • 事件委托的原理(事件冒泡)
    Understanding of event delegation via event bubbling
  • DOM API 熟悉程度
    Familiarity with the DOM API (closest, contains, addEventListener)
  • 代码的性能与灵活性
    Code performance and flexibility when handling dynamic DOM elements