【发布时间】:2023-02-07 04:13:32
【问题描述】:
我正在尝试用这个调用图块 ID。来自另一个函数中的 EventListener 的 id。
像这样:
const setGame = () => {
board = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
]
for(let r = 0 ; r < 3; r++) {
for(let c = 0 ; c < 3; c++) {
let tile = document.createElement("div")
tile.id = r.toString() + "-" + c.toString();
tile.classList.add("col-4", "box", "d-flex", "justify-content-center", "align-items-center");
tile.addEventListener("click", setTile);
document.getElementById("board").append(tile);
}
}
}
const setTile = () => {
if (gameOver) {
return;
}
let coords = this.id.split("-") //splits the id string "1-1" into an array["1", "1"]
let r = parseInt(coords[0]);
let c = parseInt(coords[1]);
board[r][c] = currPlayer;
this.innerText = currPlayer;
}
我不是“这个”的专家......我知道它从一个类中调用一个对象......在这种情况下,当我点击我正在创建的 div 元素时它会调用 tile 对象......但是在控制台上我收到此错误:
Uncaught TypeError: this.id is undefined
setTile http://127.0.0.1:5501/js/game.js:54
setGame http://127.0.0.1:5501/js/game.js:43
onload http://127.0.0.1:5501/js/game.js:27
EventHandlerNonNull* http://127.0.0.1:5501/js/game.js:26
我期待从 tiles(div 元素)获取 id 将字符串转换为数组并使用它们告诉 html 当前玩家在棋盘上的位置。
【问题讨论】:
-
您希望
this指的是什么对象,为什么? -
平铺... tile.addEventListener("click", setTile);
-
因为那时使用 setTile( ) 我试图获取它的 id 以便稍后对它做一些事情......
标签: javascript function this tic-tac-toe