我有一张带有 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/