【问题标题】:This in eventHandler equals window type , not element [duplicate]eventHandler 中的 this 等于 window type ,而不是 element [重复]
【发布时间】:2020-02-24 22:36:50
【问题描述】:

我决定将onclick 事件更改为事件侦听器,但遇到了问题。 案例 a 有效,案例 b 无效。调试器显示这等于窗口类型,而不是元素

  testName.setAttribute("onclick", "toggleTestsWindow(this)");

  // b
  testName.addEventListener("click", () => toggleTestsWindow(this));

【问题讨论】:

  • 不要将箭头函数用于事件处理程序。

标签: javascript dom-events event-listener


【解决方案1】:

这就是我通常编写事件监听器的方式:

// Identifies the HTML element
const mySpan = document.getElementById("mySpan");

// Calls `changeColor` whenever `mySpan` receives a click event
mySpan.addEventListener("click", changeColor);

// Defines `changeColor`
function changeColor(event){
  // The listener can automatically have access to the triggering event
  //   (We call it 'event' for our own convenience)

  // The event's `target` property gives us the element where
  //   the event occurred
  const targ = event.target;

  // Makes some visible change to the DOM 
  if(targ.classList.contains("blue")){
    targ.classList.remove("blue");
  }
  else{
    targ.classList.add("blue");
  }
}
.blue { background-color: lightSkyBlue; }
<span id="mySpan">CLICK ME</span>

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2022-11-11
    • 1970-01-01
    • 2020-07-05
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多