提问人:Jaroslav Tavgen 提问时间:1/8/2023 最后编辑:Jaroslav Tavgen 更新时间:1/8/2023 访问量:134
为什么事件侦听器“click”显示的是“body”元素,而不是我单击的元素?
Why Event Listener "click" shows the "body" element instead of the element that I clicked on?
问:
我去了棋盘.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”)。
但是当我点击一个带有白色碎片的正方形时,控制台打印了“身体”。当我右键单击同一个方块并选择“检查”时,它正确地在开发人员工具的“元素”部分的“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;高度:49px;”></div>“)。
显示“body”而不是正确元素的原因是什么?我应该怎么做才能让程序向我显示我点击的元素?
答:
除非你真的知道自己在做什么,否则不要只在自己身上使用。通常,当它应该使用时,它会与 99% 结合使用 - 而这正是您所需要的。event.target
.closest()
此外,不要将事件分配给 ,而是使用最接近的祖先,例如body
#myBoard
此外,使用“mousedown”事件 - 因为“click”似乎挂起,因为元素从未收到“mouseup”来实现“click”,因为单元格是以编程方式操作的
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(`mousedown`, cellClick);
由于要定位的单元格元素使用数据集属性,即:
<div
class="square-55d63 black-3c85d square-g7"
id="g7-06f7-5132-52ee-91f2-0b5b-ab5a-4157-7f9c"
data-square="g7"
>...</div>
由于该属性用于所有单元格,因此我使用了属性选择器 "[data-square]"
评论
#myBoard
评论