对于Javascript中的循环不起作用

时间:2015-02-01 07:33:26

标签: javascript html for-loop

javascript新手,但在我看来,我的html应该会生成我创建的网格。从我的js文件中没有填充tr或td元素。有谁知道为什么或我错过了什么?谢谢你的帮助。

这是我的js文件:

function showGrid() {
    var gridDiv = document.getElementById("gridDiv");
    gridDiv.innerHTML = genGrid();
}

function genGrid() {
    var html = "";
    var row = 8;
    var i = 0;
    var j = 0;
    var tdClass = "";

    for (i = row; i > 0; i--) {

        html += "<tr>";

        for (j = row; j > 0; j--) {
            var r = j % 2;
            if (r = 0) {
                tdClass = "red";
            } else {
                tdClass = "black";
            }

            html += "<td class=\"" + tdClass + "\"></td>";
        }
        html += "</tr>";
    }
    return html;
}

这是我的html文件:

<!DOCTYPE HTML>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

<html>
    <head>
        <link rel="stylesheet" type=text/css href="style.css">
        <script src="genGame.js"></script>
    </head>
    <body onload="showGrid()">

        <div id="gridDiv">
        This should get overridden
        </div>
    </body>

</html>

2 个答案:

答案 0 :(得分:1)

    <div id="gridDiv">
    This should get overridden
    </div>

应该是

    <table id="gridDiv">
    This should get overridden
    </table>

答案 1 :(得分:0)

<td></td>

中没有数据
<script>
    function showGrid() {
   var gridDiv = document.getElementById("gridDiv");
    gridDiv.innerHTML = genGrid();
}
    function genGrid() {
    var html = "";
    var row = 8;
    var i = 0;
    var j = 0;
    var tdClass = "";

    for (i = row; i > 0; i--) {

        html += "<tr>";

        for (j = row; j > 0; j--) {
            var r = j % 2;
            if (r == 0) {
                tdClass = "red";
            } else {
                tdClass = "black";
            }

            html += "<td class=\"" + tdClass + "\">-data-</td>";
        }
        html += "</tr>";
    }
    return html;
}
</script>



<body onload="showGrid()">
        <table id="gridDiv">
            This should get overridden
        </table>
 </body>

比较也应该没问题

if (r == 0) {
                tdClass = "red";
            }

link