【问题标题】:Javascript insert into table using loopJavascript使用循环插入表
【发布时间】:2021-02-23 04:22:06
【问题描述】:

我正在处理以下代码。用户选择图像并单击数据表按钮。单击按钮时,会填充相应的表格字段

function myFunction() {
  var table = document.getElementById("myTable");
  var row = table.insertRow(1);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  var cell4 = row.insertCell(3);
  cell1.innerHTML = Math.floor(Math.random() * 100);
  cell2.innerHTML = document.getElementById('img_add').files[0].name;
  cell3.innerHTML = document.getElementById('img_add').files[0].size;
  cell4.innerHTML = '<span class="p-viewer"><i class="fa fa-eye" aria-hidden="true"></i></span>';

}
<!DOCTYPE html>
<html>
<head>
    
    <title>Datatable form</title>
    
</head>
<body>
  <div class="container">
    
  
  <div style="text-align: center;padding-top: 2rem;">
    <input type="file" name="file" id="img_add">
    <button type="button" onclick="myFunction()">Data Table</button>
  </div>
    
    <img>
    <div class="col-10 center" style="margin: auto;text-align: center;">
      <div class="table-responsive">
        <table id="myTable" class="table table-bordered border-primary ">
        <thead>
          <tr>
            <th scope="col">Sr No.</th>
            <th scope="col">Image Name</th>
            <th scope="col">Image Size (bytes))</th>
            <th scope="col">View</th>
          </tr>
        </thead>
        </table>
      </div>
    </div>
  </div>
</body>
</html>

我可以逐行添加,但我想通过循环添加它。如何实现 任何帮助将不胜感激

【问题讨论】:

    标签: javascript html loops


    【解决方案1】:

    首先您需要创建表格数据。您应该将其创建为 JSON 字符串。接下来,您需要在 for 循环中调用 myFunction(),并将 JSON 数据作为参数传递给它。看到这个description of JSON

    【讨论】:

    • 除了JSON还有其他方式吗?
    • 那么 JSON 是在 JavaScript 中存储数据的标准格式。它可以在 for 循环中轻松处理。另一种选择是使用 JavaScript 数组。见:w3schools.com/js/js_arrays.asp
    猜你喜欢
    • 2021-09-21
    • 2015-03-16
    • 2015-02-13
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    相关资源
    最近更新 更多