<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
table {
width: 100%;
border: 1px solid black;
border-collapse: collapse;
}
th {
border: 1px solid black;
}
td {
border: 1px solid black;
text-align: center;
}
input {
outline: none;
}
</style>
</head>
<body>
<div style="border: solid 1px #333; margin-bottom: 10px; padding: 10px">
姓名:
<input id="name" />
年龄:
<input id="age" />
性别:
<input id="sex" />
<button onclick="addList()">添加</button>
</div>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
</thead>
<tbody id="list"></tbody>
</table>
<script>
var arr = [
{ name: "张三", age: 18, sex: "男" },
{ name: "李四", age: 19, sex: "男" },
{ name: "王五", age: 20, sex: "男" },
{ name: "赵六", age: 21, sex: "男" },
];
// 获取list 元素
var list = document.getElementById("list");
var newList = "";
// 给tbody 动态添加表格
for (var i = 0; i < arr.length; i++) {
let item = arr[i];
console.log(arr[i]);
newList += `
<tr>
<td>${item.name}</td>
<td>${item.age}</td>
<td>${item.sex}</td>
<td><a href='javascript:;' onclick='deleteList(this)'>删除</a></td>
</tr>
`;
}
list.innerHTML = newList;
// 删除操作
function deleteList(node) {
console.log(node);
list.removeChild(node.parentNode.parentNode);
}
// 添加开始
function addList() {
// 添加操作 拿到三个input 的元素的value
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
var sex = document.getElementById("sex").value;
let node = "";
node = `
<tr>
<td>${name}</td>
<td>${age}</td>
<td>${sex}</td>
<td><a href='javascript:;' onclick='deleteList(this)'>删除</a></td>
</tr>
`;
// list.innerHTML += node
list.innerHTML = list.innerHTML + node
}
</script>
</body>
</html>
原生js 动态生成表格 附带添加删除功能
于 2022-11-17 23:32:19 首次发布