我正在制作一个拼图。当我只使用html和js时,我会动态生成元素并将onclick放在每个元素上,当我单击它时,一切都很好,但是当我连接webpack时,它不起作用。我用createElement而不是串联重写了showTable函数。现在,我的函数moveThisTile没有任何错误,但是现在出现了错误Uncaught ReferenceError:未定义rowOffset,它计算了新图块位置的坐标。如何解决? 这是完整代码,错误为https://codepen.io/tomas777/pen/abZjZav 请帮忙
function showTable() {
let tbody = document.createElement("tbody");
document.querySelector('#table').appendChild(tbody);
for (let i = 0; i < rows; i++) {
let row = document.createElement("tr");
for (let j = 0; j < columns; j++) {
if (arrayForBoard[i][j] == 0) {
let cell = document.createElement("td");
cell.className = 'blank';
} else {
let cell = document.createElement("td");
cell.className = 'tile';
cell.onclick = moveThisTile(i, j);
cell.innerHTML =arrayForBoard[i][j];
}
row.appendChild(cell);
}
tbody.appendChild(row);
}
};
function moveThisTile(tableRow, tableColumn) {
if (checkIfMoveable(tableRow, tableColumn, "up") ||
checkIfMoveable(tableRow, tableColumn, "down") ||
checkIfMoveable(tableRow, tableColumn, "left") ||
checkIfMoveable(tableRow, tableColumn, "right") ) {
incrementMoves();
} else {
alert("ERROR: Cannot move tile!\nTile must be next to a blank space.");
}
if (checkIfWinner()) {
alert("Congratulations! You solved the puzzle in " + moves + " moves.");
startNewGame();
}
}
function checkIfMoveable(rowCoordinate, columnCoordinate, direction) {
rowOffset = 0;
columnOffset = 0;
if (direction == "up"){rowOffset = -1;}
else if (direction == "down"){rowOffset = 1;}
else if (direction == "left"){columnOffset = -1;}
else if (direction == "right"){columnOffset = 1;}
if (rowCoordinate + rowOffset >= 0 && columnCoordinate + columnOffset >= 0 &&
rowCoordinate + rowOffset < rows && columnCoordinate + columnOffset < columns
){
if ( arrayForBoard[rowCoordinate + rowOffset][columnCoordinate + columnOffset] == 0){
arrayForBoard[rowCoordinate + rowOffset][columnCoordinate + columnOffset] = arrayForBoard[rowCoordinate][columnCoordinate];
arrayForBoard[rowCoordinate][columnCoordinate] = 0;
showTable();
return true;
}
}
return false;
}
答案 0 :(得分:0)
我有这个错误,直接无所事事
if (arrayForBoard[i][j] == 0) {
let cell = document.createElement("td");
cell.className = 'blank';
} else {
let cell = document.createElement("td");
cell.className = 'tile';
cell.onclick = moveThisTile(i, j);
cell.innerHTML =arrayForBoard[i][j];
}
row.appendChild(cell);
您可以在if / else之外声明单元格,或在每个块内调用rowAppend单元格
let cell = null;
if (arrayForBoard[i][j] == 0) {
cell = document.createElement("td");
cell.className = 'blank';
} else {
cell = document.createElement("td");
cell.className = 'tile';
cell.onclick = moveThisTile(i, j);
cell.innerHTML =arrayForBoard[i][j];
}
row.appendChild(cell);