javascript - 如何动态向表中插入行

标签 javascript dynamic html-table rows

我有一张带有 table 头和空主体的 table :

<table id ="floodTable" class ="gradient-style">
  <thead>
    <tr>
      <th>Event Name</th>
      <th>Date</th>
      <th style="text-align:right">Return Period</th>
    </tr>
  </thead>
  <tbody>
            ...//add stuff here...      
  </tbody>
</table>

我有一个可引入 JSON 对象的 API。如果其中一个子对象满足特定条件,我想使用属性值用

的值填充新行

“事件名称”(document.getElementById("floodTable").rows[0].cells[1]),
“日期”(document.getElementById("floodTable").rows[0].cells[2]) 和
“返回周期”(document.getElementById("floodTable").rows[0].cells[3])

使用我的 API 可以拉回符合我的条件的多个项目,我可能需要创建几行。如何使用 insertRow(0) 和/或 insertCell(0) 来执行此操作?

最佳答案

您可以使用HTMLTableElement.insertRow()HTMLTableRowElement.insertCell()实现此目的的方法:

const form = document.querySelector('form');
form.addEventListener('submit', event => {
  event.preventDefault();
  event.stopPropagation();
  
  const values = Object.values(form.elements).filter(el => el.id).map(el => el.value); 
  if (values.length === 3) {
    const table = document.querySelector('#floodTable tbody');
    const row = table.insertRow(0);
  
    values.forEach((val, ind) => {
      row.insertCell(ind).innerHTML = val;
    });
    form.reset();
    window.location.href = '#floodTable';
  }
}, false);
html {
  scroll-behavior: smooth;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
      rel="stylesheet"/>
<div class="container">
  <table id="floodTable" class="table gradient-style">
    <thead>
      <tr>
        <th>Event Name</th>
        <th>Date</th>
        <th style="text-align:right">Return Period</th>
      </tr>
    </thead>
    <tbody>

    </tbody>
  </table>
  
  <div class="card">
    <form class="card-body">
      <div class="form-group">
        <label for="event">Event name:</label>
        <input type="text" class="form-control" id="event" required>
      </div>
      <div class="form-group">
        <label for="date">Date:</label>
        <input type="date" class="form-control" id="date" required>
      </div>
      <div class="form-group">
        <label for="period">Return period:</label>
        <input type="text" class="form-control" id="period" required>
      </div>

      <button type="submit" class="btn btn-primary">Add a row</button>
    </form>
  </div>
</div>

关于javascript - 如何动态向表中插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57190246/

相关文章:

Javascript 函数在 for 循环内无限期运行

javascript - jQuery .add() 使用生成的元素不起作用

c# - "Catchall"C# 中的属性?

html - 表格 Td 宽度始终为 100%

php - 尝试使用 PHP 和 html 显示来自 mysql 的数据

jquery - 使用 jQuery 的偶数/奇数表格行样式

javascript - 运行两个不同的 jQuery 函数

javascript - 用javascript添加html

go - 在 Go 中加载动态 yaml 结构

SQL Server - 动态数据透视表