Skip to content

事件监听器

一句话解释

事件监听器是 函数那个运行当 特定事件 (如点击 or keypress) occurs on HTML 元素.

用大白话说

An event listener is how JavaScript responds to user actions. You attach a function to an element that runs when a specific event happens — a click, a key press, a form submission, a mouse move, and many more.

The standard method is addEventListener: 元素.addEventListener('点击', 处理函数). You can attach multiple listeners to the same element, and remove them with removeEventListener. The handler receives an event object with details about what happened.

Events "bubble" up the DOM tree by default — a click on a button also triggers click handlers on its parent, grandparent, and so on up to the document. This enables "事件 delegation" — attaching one listener to a parent that handles events from all its children.

示例

javascript
const button = document.querySelector("#myBtn");
button.addEventListener("click", (event) => {
  console.log("Button clicked!", event.target);
});

点击事件监听器那个 logs 消息 and 点击元素当 button 是按下.

相关术语

相关资源

相关课程

解读错误信息

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

查看错误

← 返回术语表