事件监听器
一句话解释
事件监听器是 函数 registered 到运行当 特定事件 occurs on 特定元素.
用大白话说
事件监听器是 如何你 tell JavaScript "当这个事件 happens on 这个元素, 运行这个函数." 你注册 one 使用 element.addEventListener(eventType, handler). The listener stays active until you remove it or the element is destroyed.
A single element can have many listeners for different events — one for 点击, another for mouseenter, and so on. You can also have multiple listeners for the same event; they all run in the order they were added.
When you no longer need a listener, remove it with removeEventListener using the same event type and function reference. This prevents memory leaks in long-running applications, especially single-page apps where elements come and go.
示例
const input = document.querySelector("input");
function onInput(event) {
console.log("Typed:", event.target.value);
}
// Register the listener
input.addEventListener("input", onInput);
// Later, remove it
input.removeEventListener("input", onInput);addEventListener registers 处理函数; removeEventListener 移除它. 你必须通过相同函数引用到 移除它.
工作原理
- Select the element you want to watch.
- Define a handler function that runs when the event fires.
- Register the listener with
元素.addEventListener(类型, 处理函数). - The browser calls your handler every time the event occurs.
- Remove the listener with
removeEventListenerwhen no longer needed.
相关术语
相关资源
相关课程
- DOM
事件监听器是 核心的 DOM scripting
相关项目
- Random Quote Generator
Use 事件监听器到 触发 quote generation
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。