【问题标题】:How does event handler works in javascript?事件处理程序如何在 javascript 中工作?
【发布时间】:2022-02-03 22:59:52
【问题描述】:

函数执行完成,不会再被调用,但我仍然可以访问其中的事件处理程序

(function () {
 const header = document.querySelector('h1');
 header.style.color = 'red';
 header.addEventListener('click', function () {
  this.style.color = this.style.color === 'blue' ? 'red' : 'blue';
 });
})();

【问题讨论】:

  • 所以附加到 dom 元素的事件总是保持活动状态,直到它们被删除?

标签: javascript function events closures handler


【解决方案1】:

在您的 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方法将不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    相关资源
    最近更新 更多