首页 > 解决方案 > 这在 eventHandler 等于窗口类型,而不是元素

问题描述

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

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

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

标签: javascriptdom-eventsevent-listener

解决方案


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

// 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>


推荐阅读