在Table表格中,点击其中一行的操作按钮,弹出窗,点击添加可以添加多条数据
参考这个案例
<!-- 表格 -->
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John Doe</td>
<td>johndoe@example.com</td>
<td>(555) 555-1234</td>
<td><button onclick="openModal(1)">Add</button></td>
</tr>
<tr>
<td>2</td>
<td>Jane Smith</td>
<td>janesmith@example.com</td>
<td>(555) 555-5678</td>
<td><button onclick="openModal(2)">Add</button></td>
</tr>
</tbody>
</table>
<!-- 弹出窗 -->
<div id="myModal" class="modal">
<div class="modal-content">
<form onsubmit="addData(); return false;">
<input type="hidden" id="rowId" value="">
<label>Name:</label><br>
<input type="text" id="name"><br>
<label>Email:</label><br>
<input type="text" id="email"><br>
<label>Phone:</label><br>
<input type="text" id="phone"><br>
<button type="submit">Add</button>
<button type="button" onclick="closeModal()">Cancel</button>
</form>
</div>
</div>
<script>
var modal = document.getElementById("myModal");
var rowIdInput = document.getElementById("rowId");
var nameInput = document.getElementById("name");
var emailInput = document.getElementById("email");
var phoneInput = document.getElementById("phone");
// 打开弹出窗口并设置行 ID
function openModal(rowId) {
rowIdInput.value = rowId;
modal.style.display = "block";
}
// 关闭弹出窗口并重置表单
function closeModal() {
modal.style.display = "none";
nameInput.value = "";
emailInput.value = "";
phoneInput.value = "";
}
// 将数据添加到表格
function addData() {
var rowId = rowIdInput.value;
var name = nameInput.value;
var email = emailInput.value;
var phone = phoneInput.value;
var table = document.getElementById("myTable");
var row = table.rows[rowId];
var newRow = row.cloneNode(true);
newRow.cells[0].innerHTML = table.rows.length;
newRow.cells[1].innerHTML = name;
newRow.cells[2].innerHTML = email;
newRow.cells[3].innerHTML = phone;
table.appendChild(newRow);
closeModal();
}
</script>