基于前端HTML、css、JavaScript完成对于表格的增删改查
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表格的增删改查</title>
<style>
table {
width: 70%;
margin: auto;
border-collapse: collapse;
}
th, td {
border: solid gray 1px;
text-align: center;
padding: 10px;
}
.centered {
text-align: center;
}
.align-left {
margin-left: auto;
margin-right: auto;
width: 70%;
text-align: left;
}
.top{
margin-bottom: 5px;
}
button{
margin-left: 5px;
}
.color{
background-color: gray;
}
</style>
</head>
<body>
<h1 class="centered">表格的增删改查</h1>
<div class="align-left">
<button class="top" onclick="addrow()">新增人员</button>
</div>
<table id="table">
<tr class="color">
<td>姓名</td>
<td>id</td>
<td>操作</td>
</tr>
</table>
<script src="D:\learnhtml\table.js"></script>
</body>
</html>
function addrow(){
let table = document.getElementById('table');
let row = table.rows.length;
let newrow = table.insertRow(row);
let namecol = newrow.insertCell(0);
let idcol = newrow.insertCell(1);
let operationcol = newrow.insertCell(2);
let inputName = prompt("请输入您的姓名");
let inputid = prompt("请输入您的id");
namecol.innerHTML = inputName;
idcol.innerHTML = inputid;
operationcol.innerHTML = '<button οnclick="change(this)">编辑</button><button οnclick="removerow(this)">删除</button>';
}
function removerow(button){
let row = button.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function change(button) {
let row = button.parentNode.parentNode;
let nameCell = row.cells[0];
let idCell = row.cells[1];
let inputName = prompt("请输入你的姓名:");
let inputId = prompt("请输入你的ID:");
nameCell.innerHTML = inputName;
idCell.innerHTML = inputId;
}