简体   繁体   中英

How to check for values adjacent to clicked table cell and replace that value if it is “empty”

So far I have wrote a code (some functions extracted from other sites) that generates a table with 15 numbers and an empty spot.

I am wondering how to write a function that when I click any cell, and that cell is adjacent to the cell with "empty", it swaps the values of the two cells

    <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>

If anybody could help it would be great!

I would just loop from i = 1 to i < len - 1 and then do my magic on cells[i] , cells[i-1] , and cells[i+1] .

Perhaps you just want to work with innerText instead to avoid issues with quoting of <>&'" , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM