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

JavaScript棋盘棋子移动函数异常排查及解决方法

棋盘页面棋子移动功能实现问题

我正在开发一个棋盘页面,在实现棋子移动功能时遇到瓶颈,编写的moving_pieces函数未按预期工作。我的需求是获取棋子ID和棋盘格ID,将棋子添加到目标棋盘格,目前已成功获取ID但棋子无法移动。

以下是问题代码:

function moving_pieces() {
    //getting pieces ids
    let images = document.querySelectorAll('img');
    let target_piece = null;
    images.forEach(img => {
        img.addEventListener('click', function handle_move () {
            target_piece = img;
            console.log(img) //for debugging
        });
    });

    //getting squares ids
    let squares = document.querySelectorAll('.square');
    let target_square = null;
    squares.forEach(square => {
        square.addEventListener('click', function handle_id() {
            if (!square.firstChild) {
                target_square = square;
                console.log(square) //for debugging
            }
        });
    });
    target_square.appendChild(target_piece);
}

编辑记录

  • 编辑1:调整变量作用域后,ID获取部分恢复正常,但棋子仍无法移动。
  • 编辑2:已找到问题并解决——需将target_square.appendChild(target_piece);放入squares.forEach的点击事件处理函数内,功能现已正常。祝编码愉快 :)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:18:38