【问题标题】:this.id is undefined. I get this error while coding the classic tic tac toethis.id 未定义。我在编写经典井字游戏时遇到此错误
【发布时间】: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


【解决方案1】:
const setTile = (this) => {...}

【讨论】:

  • 这将是语法错误。 this 是保留关键字。除此之外 this 在这种情况下会引用 Event 对象,而不是 OP 正在寻找的元素。
猜你喜欢
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2020-02-03
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多