You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发井字棋时遇this.id未定义错误,求解决方案

解决井字棋游戏中this.id is undefined的问题

问题原因

你用箭头函数定义了setTile,箭头函数不会绑定自己的this,它的this继承自定义时的外层作用域(这里不是点击的tile元素),所以访问this.id会得到undefined。而普通函数作为事件处理函数时,this才会自动指向触发事件的DOM元素。

解决方案

方案1:将setTile改为普通函数

把箭头函数改成普通函数,点击事件触发时,this会正确指向被点击的tile元素:

function setTile() {
    if (gameOver) {
        return;
    }
    let coords = this.id.split("-")  // 此时this指向点击的tile
    let r = parseInt(coords[0]);
    let c = parseInt(coords[1]);

    board[r][c] = currPlayer;
    this.innerText = currPlayer;
}

方案2:使用事件对象的target属性

如果想保留箭头函数,可以通过事件参数获取触发事件的元素,无需依赖this:

const setTile = (event) => {
    if (gameOver) {
        return;
    }
    const tile = event.target; // 获取点击的tile元素
    let coords = tile.id.split("-")
    let r = parseInt(coords[0]);
    let c = parseInt(coords[1]);

    board[r][c] = currPlayer;
    tile.innerText = currPlayer;
}

补充说明

两种方案都能解决问题:

  • 方案1贴合你原本的代码逻辑,利用事件处理函数的this指向特性;
  • 方案2更灵活,不管函数类型是什么,都能通过事件对象获取目标元素,避免this指向混淆。

内容的提问来源于stack exchange,提问作者Ramon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:56:50