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

使用chessboard.js判断棋盘指定位置及按钮点击弹窗异常排查问询

问题修复方案

你代码存在两个核心错误,修改后即可正常运行:

  • 事件回调绑定错误:$('#checkAnswer').on('click', checkAnswer())写法中,checkAnswer()加了括号会直接执行函数,而非将函数作为回调绑定到点击事件,导致页面加载时自动触发弹窗,点击按钮反而无响应。需要去掉括号,传入函数引用即可。
  • 棋盘位置调用错误:chessboard.js中board.position是获取位置的方法,而非属性,需要加括号调用才能拿到实际位置值。

修改后的完整代码如下:

<div id="board1" style="width: 400px"></div>
<button id="clearButton">Clear Board</button>
<button id="checkAnswer">Check Answer</button>
<button id="showSolution">Show Solution</button>

<script>
  var board = Chessboard('board1', {
    draggable: true,
    dropOffBoard: 'trash',
    sparePieces: true
  })

  $('#clearButton').on('click', board.clear)
  $('#showSolution').on('click', board.start)
  // 去掉checkAnswer后面的括号,传入函数引用
  $('#checkAnswer').on('click', checkAnswer)

  function checkAnswer() {
    // 调用position()方法获取位置
    if (board.position() == 'start') {
      alert('The board is in the start position');
    } else {
      alert('The board is not in the start position')
    }
  }
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:57:03