在JavaScript中,编辑表格(table)的某一行通常涉及到以下几个基础概念:
<input>
或其他表单元素来允许用户编辑单元格内容。以下是一个简单的示例,展示如何在JavaScript中实现表格行的编辑功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Editable Table</title>
<style>
.editable {
outline: none;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<table id="myTable" border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>Action</th>
</tr>
<tr>
<td contenteditable="false">John Doe</td>
<td contenteditable="false">30</td>
<td><button onclick="editRow(this)">Edit</button></td>
</tr>
<!-- More rows can be added similarly -->
</table>
<script>
function editRow(button) {
const row = button.parentElement.parentElement;
const cells = row.getElementsByTagName('td');
for (let cell of cells) {
if (cell.cellIndex !== 2) { // Exclude the action column
cell.contentEditable = 'true';
cell.classList.add('editable');
}
}
button.textContent = 'Save';
button.onclick = function() { saveRow(this); };
}
function saveRow(button) {
const row = button.parentElement.parentElement;
const cells = row.getElementsByTagName('td');
for (let cell of cells) {
if (cell.cellIndex !== 2) { // Exclude the action column
cell.contentEditable = 'false';
cell.classList.remove('editable');
}
}
button.textContent = 'Edit';
button.onclick = function() { editRow(this); };
}
</script>
</body>
</html>
通过上述方法,可以有效地实现和管理表格行的编辑功能。
领取专属 10元无门槛券
手把手带您无忧上云