用JS控制表

时间:2015-07-20 11:41:01

标签: javascript

我写了一个非常简单的代码

<!DOCTYPE html>
<html>

<body>

<table id="myTable" border = "1"></table>

<script>

    for(var i = 1; i<=5; i++){
        var tableRow = "<tr>";
        tableRow+= "<td>" + "JS Table" + "</td>";
        tableRow+= "</tr>";        
    }

    document.getElementById("myTable").innerHTML = tableRow;

    </script>

</body>
</html> 

我想生成一个类似此代码段的表

<table border = "1">
        <tr>
            <td>JS Table</td>
        </tr>
        <tr>
            <td>JS Table</td>
        </tr>
        <tr>
            <td>JS Table</td>
        </tr>
        <tr>
            <td>JS Table</td>
        </tr>
        <tr>
            <td>JS Table</td>
        </tr>
    </table>

但是我只设置了一行,而我已经设置了5次循环。如何解决这个问题。

我还面临一个问题。如果我在头标签中写javascript,我就不会得到任何输出&amp;它说&#34; document.getElementById(&#34; myTable&#34;)。innerHTML&#34;一片空白。如何纠正它?

<!DOCTYPE html>
<html>
<head>      

    <script>

    for(var i = 1; i<=5; i++){
        var tableRow = "<tr>";
        tableRow+= "<td>" + "JS Table" + "</td>";
        tableRow+= "</tr>";        
    }

    document.getElementById("myTable").innerHTML = tableRow;

    </script>

</head>

<body>

<table id="myTable"></table>

</body>
</html> 

3 个答案:

答案 0 :(得分:2)

问题1

问题是你在for循环中一次又一次地覆盖你的tableRow。所以,你需要在for循环之外移动它。您需要将脚本更新为

var tableRow = ""; // moved outside the loop
for(var i = 1; i<=5; i++){
    tableRow += "<tr>"; // appending <tr>
    tableRow+= "<td>" + "JS Table" + "</td>";
    tableRow+= "</tr>";        
}

document.getElementById("myTable").innerHTML = tableRow;

问题2

问题即将发生,因为您正在尝试在呈现dom之前执行代码。尝试将其包装在onload函数中,即

window.onload = function(){
    // your code here
};

供参考 - https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload

答案 1 :(得分:0)

&#13;
&#13;
    <!DOCTYPE html>
    <html>
    <head>      

        <script>
        window.onload = function(){
          
          var tableRow = "";
          for(var i = 1; i<=5; i++){
            tableRow += "<tr>";
            tableRow += "<td>" + "JS Table" + "</td>";
            tableRow += "</tr>";        
          }

          document.getElementById("myTable").innerHTML = tableRow;
        };
        </script>

    </head>

    <body>

    <table id="myTable"></table>

    </body>
    </html> 
&#13;
&#13;
&#13;

答案 2 :(得分:0)

&#13;
&#13;
var   tableRow=""; 

for(var i = 1; i<=5; i++){
         tableRow += "<tr>";
        tableRow+= "<td>" + "JS Table" + "</td>";
        tableRow+= "</tr>";   

    }

    document.getElementById("myTable").innerHTML = tableRow;
&#13;
 <table id="myTable"></table>
&#13;
&#13;
&#13;