我有一张桌子,上面有一个桌子头和一个空的身体:
<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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句