前端写一个表格,可以增删改查
时间: 2023-05-17 12:05:05 浏览: 255
好的,这是一个常见的前端任务。您可以使用 HTML 和 JavaScript 来创建一个表格,并使用 AJAX 或其他技术与后端进行通信。以下是一个简单的示例代码:
HTML:
```
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- Table rows will be added dynamically with JavaScript -->
</tbody>
</table>
<button id="addRowBtn">Add Row</button>
```
JavaScript:
```
// Define a variable to keep track of the next available ID
let nextId = 1;
// Add a click event listener to the "Add Row" button
document.getElementById("addRowBtn").addEventListener("click", function() {
// Get the table body element
let tbody = document.querySelector("#myTable tbody");
// Create a new row element
let row = document.createElement("tr");
// Add cells to the row
let idCell = document.createElement("td");
idCell.textContent = nextId++;
row.appendChild(idCell);
let nameCell = document.createElement("td");
nameCell.innerHTML = '<input type="text">';
row.appendChild(nameCell);
let ageCell = document.createElement("td");
ageCell.innerHTML = '<input type="number">';
row.appendChild(ageCell);
let actionsCell = document.createElement("td");
actionsCell.innerHTML = '<button class="editBtn">Edit</button> <button class="deleteBtn">Delete</button>';
row.appendChild(actionsCell);
// Add the row to the table
tbody.appendChild(row);
// Add click event listeners to the edit and delete buttons
row.querySelector(".editBtn").addEventListener("click", function() {
// TODO: Implement edit functionality
});
row.querySelector(".deleteBtn").addEventListener("click", function() {
// TODO: Implement delete functionality
});
});
```
这段代码创建了一个包含 ID、姓名、年龄和操作的表格,并添加了一个“添加行”按钮。每次单击该按钮时,它将在表格中添加一行,并为每个单元格添加适当的元素和事件监听器。您可以根据需要添加其他功能,例如编辑和删除行。
阅读全文