首页 > 解决方案 > 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";
     }
 });
}

标签: javascripthtmldomeventsscope

解决方案


您传递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


推荐阅读