javascript - Event.target 意外成为绑定事件监听函数中的文档
问题描述
我想知道用户是否在购买衣服之前选择了尺码,
所以我将一个事件监听器附加到它的父容器,即选择区域。
如果我将绑定函数作为参数传递给事件侦听器,
则 event.target 在单击时成为文档对象。
if(selectionArea) {
selectionArea.addEventListener("click", removeWarningStyles.bind(null, event, sizeTiles,warning));
}
删除警告样式方法:
function removeWarningStyles( event, sizeTiles, warning) {
if(event.target.matches(".size-tile")) { // This becomes the document object. Why?
for(let tile of sizeTiles) {
if(tile.classList.contains("size-tile--not-properly-chosen")) {
tile.classList.toggle("size-tile--not-properly-chosen");
}
}
warning.style.visibility = "hidden";
warning.style.opacity = "0";
}
}
我什至尝试绑定 event.target 和 event.currentTarget,但它仍然不起作用。
如果我将匿名函数直接写入处理程序,
它会完美运行。但为什么?
if(selectionArea) {
selectionArea.addEventListener("click", (event) => {
if(event.target.classList.contains("size-tile")) { //becomes size-tile element correctly
for(let tile of sizeTiles) {
if(tile.classList.contains("size-tile--not-properly-chosen")) {
tile.classList.toggle("size-tile--not-properly-chosen");
}
}
warning.style.visibility = "hidden";
warning.style.opacity = "0";
}
});
}
解决方案
您传递event
的不是作为事件对象传递给您的 eventListener,而是作为 bind 的参数,在这种情况下无论如何这都是无用的,因为您绑定到全局上下文并且您的函数不包含关键字this
。
selectionArea.addEventListener("click", removeWarningStyles.bind(null, event, sizeTiles,warning));
真的应该
selectionArea.addEventListener('click', e=>{
removeWarningStyles(e, sizeTiles, warning);
});
其实我很想
selectionArea.onclick = e=>{
removeWarningStyles(e, sizeTiles, warning);
}
因为删除或覆盖事件更容易。
附言
请记住,只有Event Object 作为参数传递给 eventListener 函数,而 eventListener 函数的this
上下文是该方法所属的 Object,通常情况下是 Element。您还应该知道在 eventListening 函数中调用另一个函数时,它的this
上下文不会绑定到元素。箭头函数当然会以不同的方式工作,因为它们this
会上升到一个作用域级别,它会停留在哪里,所以绑定对它们毫无意义。换句话说,您不能在箭头函数中使用this.value
或,就像在作为 eventListener 的普通函数中一样。this.style.color
推荐阅读
- node.js - 如何使用 React ckfinder Node.js 上传图像
- android - 使用Android Navigation Component,如何使actionBar透明并在单个Fragment中使布局全屏?
- python - PyPDF4 - 导出的 PDF 文件太大
- ios - 无法在测试框架中使用 XCTUnwrap
- android - 我们如何在android中的两个活动之间传递扩展类的对象?
- pyspark - 在python中以编程方式提交pyspark作业而不使用提交pyspark
- laravel - 具有多个连接的数据库查询的雄辩查询
- python - python中的初学者错误,如何修复这种“lat”类型
不能转换为浮动 - python - 如果变音符号位于行尾,如何在变音符号后添加空格
- html - 如何修复 CSS 网格区域以在 IE11 中工作?