如何使用javascript创建表

时间:2015-01-06 09:48:16

标签: javascript html css

我想用javascript创建表。我想问一下用户,表的宽度和高度(1个单元格是1个单位)。然后,当创建表时,如果用户单击其中一个单元格,则颜色会发生变化。我写了这么代码,但我几乎被卡住了。

HTML代码:                                     

    <script src="script.js"></script>
    <style>
        #chessboard{border: 1px solid black; border-collapse: collapse}
        td {width: 40px; height: 40px}

        tr:nth-child(odd) td:nth-child(even) {background: black}
        tr:nth-child(even) td:nth-child(odd) {background: black}
    </style>
</head>
<body onload="myFunction()">
    <div>
        <table id="chessboard">

        </table>
    </div>
</body>

JAVASCRIPT:

   var width = parseInt(prompt("Put width", "here"));
   var height = parseInt(prompt("Put height", "here"));

      function myFunction()
      {
         var tabel = document.getElementById("chessboard");

        for (i = 0; i < height; i++){
        var row = tabel.insertRow(i);
        };

        for (j = 0; j < width; j++){
        var celica = document.getElementByTagName("tr").rows[j];
        var x = celica.insertCell(j);
        };

        }

1 个答案:

答案 0 :(得分:1)

不要分别遍历行中所需的列,而是尝试嵌套for循环。它更容易,意味着您不必再次笨拙地查找行。

仅供参考,没有getElementByTagName,只有getElementsByTagName。

  var width = parseInt(prompt("Put width", "here"));
  var height = parseInt(prompt("Put height", "here"));

  function myFunction() {
    var table = document.getElementById("chessboard");

    for (var i = 0; i < height; i++) {
      var row = table.insertRow(i);
      
      for (var j = 0; j < width; j++) {
        row.insertCell(j);
      }
    };

  }
<head>
  <script src="script.js"></script>
  <style>
    #chessboard {
      border: 1px solid black;
      border-collapse: collapse
    }
    td {
      width: 40px;
      height: 40px
    }
    tr:nth-child(odd) td:nth-child(even) {
      background: black
    }
    tr:nth-child(even) td:nth-child(odd) {
      background: black
    }
  </style>
</head>

<body onload="myFunction()">
  <div>
    <table id="chessboard">

    </table>
  </div>
</body>