我编写了一个代码,它有一个 4x4 表格,每个单元格中的数字 1-15 加上一个单元格中的“空”。
当我将任何相邻的单元格(上方、左侧、右侧或下方)单击为“空”时,它会交换两个值。它似乎在中间 2 行运行良好,但在顶部和底部行不行。谁能指出问题?
<script type="text/javascript">
var test = 0;
var startNumber = 0;
var arrayNumbers = new Array()
for (i = 0; i < 16; ++i) {
if (i == 15) { arrayNumbers[i] = "empty"; }
else {
++startNumber;
arrayNumbers[i] = startNumber
}
}
shuffle(arrayNumbers);
document.write("<table id = \"table1\" border = \"1\">")
for (k = 0; k < 4; ++k) {
document.write("<tr>")
for (i = 0; i < 4; ++i) {
document.write("<td>" + arrayNumbers[test] + "</td>");
++test
}
document.write("</tr>")
}
document.write("</table>")
// Table Made
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var table = document.getElementById('table1'),
cells = table.getElementsByTagName('td');
var i = 0, len = cells.length
for (var i = 0, len = cells.length; i < len; i++) {
cells[i].onclick = function (index) {
return function () {
if (cells[index - 1].innerHTML == "empty" && index !== 4 && index !== 8 && index !== 12) {
cells[index - 1].innerHTML = cells[index].innerHTML;
cells[index].innerHTML = "empty";
}
else if (cells[index + 1].innerHTML == "empty" && index !== 3 && index !== 7 && index !== 11) {
cells[index + 1].innerHTML = cells[index].innerHTML;
cells[index].innerHTML = "empty";
}
if (cells[index - 4].innerHTML == "empty") {
cells[index - 4].innerHTML = cells[index].innerHTML;
cells[index].innerHTML = "empty";
}
if (cells[index + 4].innerHTML == "empty") {
cells[index + 4].innerHTML = cells[index].innerHTML;
cells[index].innerHTML = "empty";
}
}
}
(i)
}
</script>