题目:
实现表格的添加与删除
HTML部分:
<input type="text" name="idCard" id="ipt1" />
<input type="text" name="username" id="ipt2" />
<input type="button" value="按钮" id="btn" />
<table>
<thead>
<tr>
<th>学号</th>
<th>姓名</th>
<th>操作</th>
</tr>
</thead>
<tbody id="list">
<!-- <tr>
<td></td>
<td></td>
<td></td>
</tr> -->
</tbody>
</table>
JS部分:
var btn = document.querySelector("#btn");
// console.log(btn);
var arr = [];
btn.onclick = function () {
var sNum = document.querySelector("#ipt1");
var sName = document.querySelector("#ipt2");
var Num = sNum.value;
var Name = sName.value;
var obj = { id: Num, name: Name };
arr.push(obj);
console.log(arr);
var str = "";
arr.forEach(function (v) {
str += `<tr>
<td>${v.id}</td>
<td>${v.name}</td>
<td><button onclick = "del(${v.id})">删除</button></td>
</tr>`;
});
var list = document.querySelector("#list");
list.innerHTML = str;
sNum.value = "";
sName.value = "";
};
function del(num) {
var index = arr.indexOf(function () {
return v.id == num;
});
arr.splice(index, 1);
var str = "";
arr.forEach(function (v) {
str += `<tr>
<td>${v.id}</td>
<td>${v.name}</td>
<td><button onclick = "del(${v.id})">删除</button></td>
</tr>`;
});
var list = document.querySelector("#list");
list.innerHTML = str;
}
运行结果: