0

到目前为止,我已经编写了一个代码(一些从其他站点提取的函数),它生成了一个包含 15 个数字和一个空白点的表格。

我想知道如何编写一个函数,当我单击任何单元格并且该单元格与“空”单元格相邻时,它会交换两个单元格的值

    <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

    document.write("askjd")

    document.write(document.getElementById("table1").getElementsByTagName("tr")[2])

    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');

    for (var i = 0, len = cells.length; i < len; i++) {
        cells[i].onclick = function () {
            window.alert(this.innerHTML);



        }
    }

</script>

如果有人可以提供帮助,那就太好了!

4

1 回答 1

0

我会从i = 1to循环i < len - 1,然后在cells[i],cells[i-1]cells[i+1].

也许您只想使用 innerText 来避免引用<>&'"等问题。

于 2013-09-01T10:04:57.190 回答