首页 > 解决方案 > 如何遍历 html 中的表并使用 javascript 迭代它们的值

问题描述

我正在构建一个网格(20 行和 20 列(正方形)),但努力在表值上循环以实际制作网格

我提供了有关 html 代码的更多信息..

图片在评论中提供

    <body>
        <h1>Pixel Art Maker</h1>

    <h2>Choose Grid Size</h2>
        <form id="sizePicker">
            Grid Height:  <!--- Creating input element to input height --->
            <input type="number" id="inputHeight" name="height" min="1" value="1"> 
            Grid Width: <!--- Creating input element to input width --->
            <input type="number" id="inputWidth" name="width" min="1" value="1">
            <input type="submit">
        </form>

    <h2>Pick A Color</h2>
    <input type="color" id="colorPicker"> <!--- Creating imput element to input a certain color --->

    <h2>Design Canvas</h2>
    <table id="pixelCanvas"> <tr> <td>  </td>  </tr> </table>
    <!--- Creating the table --->

    <script src="designs.js"></script>
    </body>

    table,
    tr,
    td {
        border: 1px solid black;
    }
    tr {
        height: 20px; //some how this is working as it's the same as 
                      //td when i edit it the td gets edited aswell
        width: 20px;
    }

    td {
        height: 20px; //same as here
        width: 20px;
    }

    const lTable = document.querySelector("pixelCanvas"); 
    //Selecting my table and storing it in a variable

    let height = document.querySelector("#inputHeight");
    //Storing the value on the input height element
    let width = document.querySelector("#inputWidth");
    //Storing the value of the input width element

    function makeGrid() {

    //This is the main problem i can't figure out how to iterate the value
    // to make the actual grid and give it the event listener

}

标签: javascripthtmlcss

解决方案


除非您想向 API 提交数据,否则您不需要表单。

在这里为您的问题找到一个最小的解决方案:

    
    
    function makeGrid() {
      let height = document.querySelector("#inputHeight").value;
      //Storing the value on the input height element
      let width = document.querySelector("#inputWidth").value;
      //Storing the value of the input width element
      //Selecting my table and storing it in a variable
      const lTable = document.querySelector("#pixelCanvas"); 
      //This is the main problem i can't figure out how to iterate the value
      // to make the actual grid and give it the event listener
      for (var i=0; i< height;i++) {
        var row = lTable.insertRow(i);
        for (var j=0; j< width;j++) {
          row.insertCell(j);
        }
      }
    }
table {
  border: 1px solid black;
}
table td {
  border: 1px solid black;
  height: 20px; 
  width: 20px;
}
<div>
  <label for="inputHeight">Height</label>
  <input type="text" id="inputHeight" value="0"/>
</div>
<div>
  <label for="inputWidth">Width</label>
  <input type="text" id="inputWidth" value="0"/>
</div>
<input type="submit" value="Draw" onClick="makeGrid()"></input>
<table id="pixelCanvas"></table>


推荐阅读