【问题标题】:Why Event Listener "click" shows the "body" element instead of the element that I clicked on?为什么事件侦听器“单击”显示“body”元素而不是我单击的元素?
【发布时间】:2023-01-08 02:17:46
【问题描述】:

我去了 chessboard.js https://chessboardjs.com/examples#5000 ,打开开发者工具并粘贴了下面的代码

document.body.addEventListener(`click`, a1);
function a1(){
   console.dir(event.target);
}

当我点击一个空的国际象棋方格时,控制台打印出正确的结果(例如,“div#e5-b9f9-a5bc-69e1-3e5a-4b82-b2bc-ffe4-966c.square-55d63.black-3c85d.square- e5”)。

但是当我点击上面有棋子的方格时,控制台打印出“body”。当我右键单击同一个方块并选择“检查”时,它在开发人员工具的“元素”部分的“div”元素内正确显示了一个“img”元素(例如,<div class="square-55d63 white-1e1d7 square-e2" style="width:49px;height:49px;" id="e2-f699-d489-4d29-2e6f-2a64-c1ec-e26f-fb62" data-square="e2"><img src="chessboard/img/chesspieces/wikipedia/wP.png" alt="" class="piece-417db" data-piece="wP" style="width:49px;height:49px;"></div> ”)。

显示“正文”而不是正确元素的原因是什么?我应该怎么做才能让程序显示我点击的元素?

【问题讨论】:

  • 可能有一个事件处理程序会停止对空方块的传播,但不会停止对已占用方块的传播。
  • 无法重现。空 -> DIV,棋子 -> IMG -> minimal reproducible example

标签: javascript events event-handling dom-events


【解决方案1】:

只是使用event.target 除非你真的知道你在做什么。通常它与 .closest() 结合使用,它在应该使用时为 99% - 这正是您也需要的。

此外,不要将事件分配给body,而是使用最近的祖先,如#myBoard

function cellClick (evt){
   const elCell = evt.target.closest("[data-square]");
   if (!elCell) return; // Do nothing. No cell element.

   // Otherwise do...
   console.dir(elCell);
}

document.querySelector("#myBoard").addEventListener(`click`, cellClick);

【讨论】:

  • 您的示例与 OP 完全不同,并不总是可以在元素本身上设置事件侦听器。
猜你喜欢
  • 2020-04-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
相关资源
最近更新 更多