我正在尝试构建数独游戏。目前,我正在进入数组并基于此构建GUI。当我在输入字段上使用事件侦听器时,就会发生该错误-每次更改任何输入时,右下角的输入也会随之更改。我不知道为什么会这样,有人可以帮忙吗?
class Sudoku {
newGame (newBoard) {
let td, tr, inputEl;
let table = document.createElement('table');
table.classList.add('sudoku-container')
// Go over the rows
for (let i = 0; i < 9; i++) {
tr = document.createElement('tr');
// Go over columns
for (var j = 0; j < 9; j++) {
// Build the input
inputEl = document.createElement('input');
inputEl.setAttribute('maxlength', 1);
inputEl.addEventListener('input', (e) => {
inputEl.value = e.target.value;
});
// If input value is not 0 then show value
if (newBoard[i][j]) {
inputEl.value = newBoard[i][j];
inputEl.setAttribute('readonly', true);
}
td = document.createElement('td');
td.appendChild(inputEl);
// Calculate the section ID
let sectIDi = Math.floor(i / 3);
let sectIDj = Math.floor(j / 3);
// Set the design for different sections
if ((sectIDi + sectIDj) % 2 === 0) {
td.classList.add('sudoku-section-one');
} else {
td.classList.add('sudoku-section-two');
}
// Build the row
tr.appendChild(td);
}
// Append to table
table.appendChild(tr);
document.querySelector('body').appendChild(table);
}
// Return the GUI table
return table;
}
}
这是jsfiddle:https://jsfiddle.net/h9gab7jz/1/