为何调用appendChild移动棋子后,classList.contains返回false?
跳棋棋子移动后点击判断失效问题解决
问题现象
调试跳棋项目时,通过DOM操作实现gold-piece棋子的移动:移除原单元格的棋子元素,在目标单元格新建带有gold-piece类的div并添加进去。但出现异常:棋子移动前,点击它时event.target.classList.contains('gold-piece')正常返回true;移动到新单元格后,点击该棋子,这个判断始终返回false。
移动逻辑代码
if (lastcell != null) { console.log("previous tapped cell is not null"); //get the cell that was previously tapped //make sure the rows and the columns have a difference of 1 let x1 = lastcell[0]; let y1 = lastcell[1]; if (col < y1) { //it is a move towards the left if ((y1 - col) == 1 && (row - x1) == 1) { //the move is valid let original = getTableCell(table, x1, y1); let child = original.querySelector("div.gold-piece"); if (child != null) { original.removeChild(child); } //move the piece to the target cell let target = getTableCell(table, row, col); const div = document.createElement("div"); div.classList.add("gold-piece"); target.appendChild(div); B = true; A = false; } else { console.log("the move is not valid"); A = true; B = false; //clear the dictionary after a move lastTappedA = {} } } else { //it is a move towards the right if ((col - y1) == 1 && (row - x1) == 1) { //the move is valid let original = getTableCell(table, x1, y1); let child = original.querySelector("div.gold-piece"); if (child != null) { original.removeChild(child); } //move the piece to the target cell let target = getTableCell(table, row, col); const div = document.createElement("div"); div.classList.add("gold-piece"); target.appendChild(div); B = true; A = false; lastTappedA = {} } else { console.log("the move is not valid"); A = true; B = false; } } }
问题根源
排查后发现,gold-piece的点击事件监听代码被包裹在if (row < 3)的条件判断中。当棋子移动到第3行及以上的单元格时,新创建的gold-piece元素没有被绑定点击事件,导致点击时event.target.classList.contains('gold-piece')的判断逻辑根本不会触发,自然返回false。
解决方案
将gold-piece的点击事件监听代码从if (row < 3)的条件块中移出,确保所有行的单元格中创建的gold-piece元素都能正确绑定点击事件。
内容的提问来源于stack exchange,提问作者Anthony Kinyua
相关产品推荐
相关产品推荐

