簡體   English   中英

如何在表中動態插入行

[英]How to dynamically insert rows into a 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM