函数执行完毕,不再被调用,但我仍然可以访问中的事件处理程序
(function () {
const header = document.querySelector('h1');
header.style.color = 'red';
header.addEventListener('click', function () {
this.style.color = this.style.color === 'blue' ? 'red' : 'blue';
});
})();
在您的JavaScript代码中,您正在将事件处理程序附加到DOM中的对象。
由于元素不会消失,所以在IIFE运行后,即使header
变量已不存在,处理程序仍会附加到它。
document.querySelector("h1").click()
console.log("color after first click: " + document.querySelector("h1").style.color);
(function () {
const header = document.querySelector('h1');
header.style.color = 'red';
header.addEventListener('click', function () {
this.style.color = this.style.color === 'blue' ? 'red' : 'blue';
});
})();
document.querySelector("h1").click()
console.log("color after second click: " + document.querySelector("h1").style.color)
document.querySelector("h1").click()
console.log("color after third click: " + document.querySelector("h1").style.color)
<h1>Test</h1>
如果您通过onclick
属性附加事件侦听器,您可以更好地看到这一点,因为通过addEventListener
添加的事件之后无法轻松访问:
console.log(document.querySelector("h1").onclick); // -> null
(function () {
const header = document.querySelector('h1');
header.style.color = 'red';
header.onclick = function () {
this.style.color = this.style.color === 'blue' ? 'red' : 'blue';
}
})();
document.querySelector("h1").click()
console.log(document.querySelector("h1").onclick) // -> your function
<h1>Test</h1>
如果要从元素中删除事件侦听器,则必须具有对所附加函数的引用,否则removeEventListener
方法将不起作用。