search

Home  >  Q&A  >  body text

javascript - Why does creating a multi-row and multi-column table only have a table in one row at the end?

I wrote a function myself to create a table with multiple rows and columns, but after writing it, I found that I could only create one row and multiple columns.

    <p id="game-box"></p>
    <script>
            var Tab=createGrids(16,10);
            var gameBox=document.getElementById("game-box");
            gameBox.appendChild(Tab);
            // 创建网格
            function createGrids(row,col) {
                var Tab=document.createElement("table");
                var Tbody=document.createElement("tbody");
                var i=0,j=0;
                while(i<row) {
                    var Tr=document.createElement("tr");
                    while(j<col) {
                        var Td=document.createElement("td");
                        Tr.appendChild(Td);
                        j++;
                    }
                    Tbody.appendChild(Tr);
                    i++;
                }
                Tab.appendChild(Tbody);
                return Tab;
            }
    </script>
淡淡烟草味淡淡烟草味2782 days ago617

reply all(1)I'll reply

  • 滿天的星座

    滿天的星座2017-05-16 13:38:39

    Because you run while(i<row) 的结束时候 while(j<col)中的 j 已经是10了哦,所以,第二遍循环 i以后,创建的tr里面都是没有 td 的,因为没有走进while(j<col) for the first time,

    You can change it to this

        <p id="game-box"></p>
        <script>
                var Tab=createGrids(16,10);
                var gameBox=document.getElementById("game-box");
                gameBox.appendChild(Tab);
                // 创建网格
                function createGrids(row,col) {
                    var Tab=document.createElement("table");
                    var Tbody=document.createElement("tbody");
                    var i=0;
                    while(i<row) {
                        var Tr=document.createElement("tr");
                        var j=0;
                        while(j<col) {
                            var Td=document.createElement("td");
                            Tr.appendChild(Td);
                            j++;
                        }
                        Tbody.appendChild(Tr);
                        i++;
                    }
                    Tab.appendChild(Tbody);
                    return Tab;
                }
        </script>

    It should be fine

    reply
    0
  • Cancelreply