Event.target意外地成为绑定事件侦听器函数中的文档



我想知道用户是否在购买衣服之前选择了尺码,
所以我在它的父容器选择区域附加了一个事件监听器。

带有选择瓷砖的产品卡

选择区域HTML标记

如果我将绑定函数作为参数传递给事件侦听器,
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不是作为Event Object传递给您的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);
}

因为删除或覆盖事件更容易。

PS

请记住,only事件对象作为参数传递给eventListener函数,而eventListener功能的this上下文是该方法所属的对象,在本例中为Element。您还应该知道,当调用eventListening函数中的另一个函数时,其this上下文不会绑定到Element。当然,Arrow函数的工作方式不同,因为它们的this会上升到作用域级别,并停留在该级别,所以绑定对它们来说毫无意义。换句话说,不能在箭头函数中使用this.valuethis.style.color,就像在eventListener的普通函数中一样。

最新更新