文档
- https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener
- https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/removeEventListener
语法
// 添加事件监听 target.addEventListener(type, listener[, options]); target.addEventListener(type, listener[, useCapture=false]); // 移除事件监听 target.removeEventListener(type, listener[, options]); target.removeEventListener(type, listener[, useCapture=false]);
示例
<button onclick="addClickEventListener()">添加事件监听</button> <button onclick="removeClickEventListener()">移除事件监听</button> <script> // 事件处理函数 function handleEvent(event) { console.log(event) } // 添加事件监听 function addClickEventListener() { console.log('addClickEventListener') document.addEventListener('click', handleEvent) } // 移除事件监听 function removeClickEventListener() { console.log('removeClickEventListener') document.removeEventListener('click', handleEvent) } </script>