I am currently programming a checkers game for a high school project. This code is a part of what I have which has an issue):
function CreateBoard() {
var board = document.createElement("table");
board.cellSpacing = 0;
for (var i = 0; i < 8; i++) {
var tr1 = document.createElement("tr");
for (var j = 0; j < 8; j++) {
var td1 = document.createElement("td");
td1.setAttribute("id", "td" + i + j);
td1.addEventListener("click", function () { Check(i, j); });
if (i % 2 == 0) {
if (j % 2 == 0)
td1.style.backgroundColor = "beige";
else
td1.style.backgroundColor = "black";
}
else {
if (j % 2 == 0)
td1.style.backgroundColor = "black";
else
td1.style.backgroundColor = "beige";
}
tr1.appendChild(td1);
}
board.appendChild(tr1);
}
document.body.appendChild(board);
}
function Check(i, j) {
alert("Check i: " + i);
alert("Check j: " + j);
}
Now, here's the problem: When I run my code using HTML, I see the board perfectly. However, when I click one of the cells testing my event listeners, I get that i
and j
are always equal to 8. My teacher helped me figure out that the problem arises from the fact that the event listeners are loaded after the loop runs, so that i
and j
always get their last value, which is 8. She hasn't provided me with a solution yet. Does anyone know how to solve this problem? Is anyone willing to help me with this? It will help me enormously.