原生 JS 事件绑定与移除
事件绑定函数实现
原理说明
- 核心机制:兼容不同浏览器的事件绑定 API。
- 参数说明
target:目标 DOM 元素。
type:事件类型(如 "click"、"mouseover",无需 on 前缀)。
func:事件触发时执行的回调函数。
实现代码
function addEvents(target, type, func) {
if (target.addEventListener) {
target.addEventListener(type, func, false);
} else if (target.attachEvent) {
target.attachEvent(`on${type}`, func);
} else {
target[`on${type}`] = func;
}
}
事件移除函数实现
原理说明
- 核心机制:兼容不同浏览器的事件移除 API,移除方式需与绑定方式严格对应。
- 参数说明
target:目标 DOM 元素。
type:事件类型。
func:需移除的回调函数引用(必须与绑定时传入的为同一函数引用)。
实现代码
function removeEvents(target, type, func) {
if (target.removeEventListener) {
target.removeEventListener(type, func, false);
} (target.) {
target.(, func);
} {
target[] = ;
}
}