javascript - 这在 eventHandler 等于窗口类型,而不是元素
问题描述
我决定将onclick
事件更改为事件侦听器并遇到问题。案例 a 有效,案例 b 无效。调试器显示这等于窗口类型,而不是元素
testName.setAttribute("onclick", "toggleTestsWindow(this)");
// b
testName.addEventListener("click", () => toggleTestsWindow(this));
解决方案
这就是我通常编写事件监听器的方式:
// 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>
推荐阅读
- java - 如果管道崩溃,如何将消息发送到队列
- javascript - 确保用户在“正确的”网页上?
- visual-studio-2017 - 如何修复 TDS Hedgehog 部署错误:'Exception The given key was not present in the dictionary.'?
- google-apps-script - 如何同时忽略 for 循环中的空白和非空白值
- rpm - 如何在 rpm 规范文件中直接覆盖 optflags?
- html - 如何在联系表格 7 中添加图像而不是复选框的选项?
- scala - 如何在不阻塞 CPU 的情况下执行无限循环
- excel - VBA计算Excel两个数组之间的绝对差异
- javascript - 我可以使用 detox 测试框架来测试 react + react 原生应用吗?
- php - Yii2 Facebook oauth - 违反完整性约束:1048 - 列“电子邮件”不能为空