table 点击编辑 修改当前行代码
时间: 2023-09-18 07:06:46 浏览: 62
好的,以下是一个简单的示例代码,演示了如何在表格中点击某一行的“编辑”按钮后,弹出一个编辑表单,用户可以在表单中修改该行的数据,最后点击保存按钮保存修改后的数据并更新到表格中对应的行。
HTML 代码:
```html
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Tom</td>
<td>18</td>
<td><button class="editBtn">编辑</button></td>
</tr>
<tr>
<td>2</td>
<td>Jerry</td>
<td>20</td>
<td><button class="editBtn">编辑</button></td>
</tr>
</tbody>
</table>
<div id="editForm" style="display:none;">
<h3>编辑信息</h3>
<form>
<div>
<label>ID:</label>
<input type="text" id="editId" readonly>
</div>
<div>
<label>Name:</label>
<input type="text" id="editName">
</div>
<div>
<label>Age:</label>
<input type="text" id="editAge">
</div>
<button type="button" id="saveBtn">保存</button>
<button type="button" id="cancelBtn">取消</button>
</form>
</div>
```
JavaScript 代码:
```javascript
$(function() {
// 给编辑按钮添加点击事件
$('.editBtn').click(function() {
// 获取当前行的数据
var id = $(this).parent().siblings(':first').text();
var name = $(this).parent().siblings(':eq(1)').text();
var age = $(this).parent().siblings(':eq(2)').text();
// 将数据填充到表单中
$('#editId').val(id);
$('#editName').val(name);
$('#editAge').val(age);
// 显示编辑表单
$('#editForm').show();
});
// 给保存按钮添加点击事件
$('#saveBtn').click(function() {
// 获取表单中的数据
var id = $('#editId').val();
var name = $('#editName').val();
var age = $('#editAge').val();
// 更新表格中对应行的数据
$('#myTable tbody tr').each(function() {
if ($(this).find('td:first').text() == id) {
$(this).find('td:eq(1)').text(name);
$(this).find('td:eq(2)').text(age);
return false; // 跳出 each 循环
}
});
// 关闭编辑表单
$('#editForm').hide();
});
// 给取消按钮添加点击事件
$('#cancelBtn').click(function() {
// 关闭编辑表单
$('#editForm').hide();
});
});
```
这段代码使用了 jQuery 来简化 DOM 操作。在点击“编辑”按钮时,使用 jQuery 的 siblings 方法获取当前行的数据,并将数据填充到表单中。在点击“保存”按钮时,使用 jQuery 的 each 方法遍历表格中所有行,找到对应的行并更新数据。最后,使用 jQuery 的 hide 方法关闭编辑表单。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)