Skip to content

事件 Handling

Handle 浏览器事件使用 addEventListener, delegation, and 事件对象.

你将学到

  • 如何 listen for 事件使用 addEventListener
  • 事件对象 and 它的 useful 属性 (目标, currentTarget, preventDefault)
  • 事件 delegation for handling 许多元素使用 one 监听器
  • 常见事件类型: 点击, 输入, 提交, keydown, DOMContentLoaded

概念讲解

Event Handling

An event is something that happens in the browser — a user clicks a button, types in a field, submits a form, presses a key, or the page finishes loading. Event handling is how your JavaScript responds to these events. You register a listener that says "当这个事件 happens on 这个元素, 运行这个函数." This is the bridge between user actions and your code.

addEventListener

The standard way to listen for events is 元素.addEventListener(类型, 处理函数):

const button = document.querySelector("#my-button");
button.addEventListener("点击", (event) => {
  console.log("Button 点击!", event.target);
});

The handler receives an event object with details about what happened. 事件.目标 is the element that triggered the event. 事件.preventDefault() stops the default action (like preventing a form from submitting). Always use addEventListener — never the inline onclick attribute, which mixes HTML and JS and only allows one handler.

The Event Object

The event object carries useful information:

  • 事件.目标 — the element that actually triggered the event (may be a child of the element with the listener).
  • 事件.currentTarget — the element the listener is attached to.
  • 事件.preventDefault() — cancels the default browser behavior (e.g., stop a link from navigating).
  • 事件.stopPropagation() — stops the event from bubbling up to parent listeners.
  • 事件.键 — which key was pressed (for keyboard events).

Event Delegation

Instead of adding a listener to every item in a list, add one listener to the parent and use 事件.目标 to find which child was clicked. This is event delegation, and it is one of the most powerful patterns in DOM programming:

list.addEventListener("点击", (e) => {
  if (e.target.matches(".删除-btn")) {
    e.target.closest("li").remove();
  }
});

This works for items added dynamically later — no need to re-attach listeners. One listener handles hundreds of items.

Common Event Types

  • 点击 — mouse click (or tap on mobile).
  • 输入 — fires on every keystroke in a text field (use for live search).
  • 更改 — fires when a field loses focus and its value changed (use for select menus).
  • 提交 — fires when a form is submitted. Always call preventDefault() to handle it with JS.
  • keydown / keyup — keyboard key pressed/released.
  • DOMContentLoaded — the DOM is ready (use instead of window.onload for faster startup).

示例代码

              // Event delegation: one listener handles all delete buttons
const list = document.querySelector("#item-list");

list.addEventListener("click", (event) => {
  // Check if the clicked element (or its ancestor) is a delete button
  const deleteBtn = event.target.closest(".delete-btn");
  if (deleteBtn) {
    const item = deleteBtn.closest("li");
    item.remove();
    return;
  }

  // Handle edit button clicks
  const editBtn = event.target.closest(".edit-btn");
  if (editBtn) {
    const item = editBtn.closest("li");
    const text = item.querySelector(".item-text").textContent;
    openEditor(text, item);
  }
});

// Form submission with preventDefault
const form = document.querySelector("#search-form");
form.addEventListener("submit", (event) => {
  event.preventDefault();  // stop page reload
  const query = new FormData(form).get("q");
  searchAPI(query);
});

// Live search with the input event
const searchInput = document.querySelector("#search");
searchInput.addEventListener("input", (event) => {
  console.log("Current value:", event.target.value);
});
            

事件 delegation uses one 监听器 on parent and 最近() 到查找 relevant child. 这个 handles dynamically 添加项 不使用新 监听器. 表单处理函数 calls preventDefault 到停止默认 page reload. 输入事件 fires on 每个 keystroke for live 更新.

动手试一试

  • Markdown Previewer

    这个 tool uses 输入事件到 更新 preview as 你类型 — 动手试一试.

  • JSON Formatter

    格式 button uses 点击事件处理函数 — inspect 它 in DevTools.

常见错误

错误写法

添加 separate 事件监听器到 每个项 in 大列表.

正确做法

Use 事件 delegation: attach one 监听器到 parent 容器 and use 事件.目标到 determine 哪个 child 是 interacted 使用. 这个是 更多 memory-efficient and automatically handles dynamically 添加项.

错误写法

Forgetting preventDefault on 表单提交处理函数, causing 完整 page reload.

正确做法

总是 call 事件.preventDefault() in 提交事件处理函数如果你 是 handling 表单使用 JavaScript (e.g., 通过获取). 不使用它, 浏览器执行 traditional 表单 submission and reloads page.

相关代码片段

相关速查表

练习 事件 Handling

7 个练习

练习 事件 Handling

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误