题目描述
可以删除却无法添加
题目来源及自己的思路
相关代码
粘贴代码文本(请勿用截图)
<!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 {
border-collapse: collapse;
}
table td {
width: 100px;
line-height: 30px;
border: 1px solid #000;
text-align: center;
}
</style>
</head>
<body>
姓名: <input type="text" id="name"><br>
年龄: <input type="number" id="age"><br>
姓名: 男<input type="radio" id="sex" value="男">
女<input type="radio" id="sex" value="女">
保密<input type="radio" id="sex" value="保密"> <br>
<button id="add">添加</button>
<table>
<thead>
<tr>
<td>序号</td>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
<td>删除</td>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
var arr = [{
name: "张三",
age: "18",
sex: "男"
},
{
name: "李四",
age: "15",
sex: "男"
},
{
name: "夏洛",
age: "34",
sex: "女"
},
{
name: "外星人",
age: "3",
sex: "保密"
}
];
var tbody = document.querySelector("tbody");
var btn = document.querySelector("#add");
setTab();
btn.onclick = function () {
var ipName = document.querySelector("#name").value;
var ipAge = document.querySelector("#age").value;
var ipSex = document.querySelector("#sex");
var sexValue = 0;
ipSex.forEach(function (e) {
if (e.checked === true) {
sexValue = e.value;
}
});
var obj = {
name: ipName,
age: ipAge,
sex: sexValue,
}
arr.push(obj);
setTab();
}
function setTab() {
var str = "";
arr.forEach(function (e, key) {
str += "<tr>";
str += `<td>${key+1}</td>`;
for (var i in e) {
str += `<td>${e[i]}</td>`;
}
str += `<td><button index="${key}">删除</button></td>`;
str += "</tr>";
})
tbody.innerHTML = str;
}
tbody.onclick = function (item) {
item = item || window.event;
var eTag = item.target || item.srcElement;
if (item.target.tagName == "BUTTON") {
var index = eTag.getAttribute("index");
arr.splice(index, 1);
item.target.remove();
setTab();
}
}
</script>
</body>
</html>
添加报错了