一丶准备工作
1.一个lable,四个input,便于用户输入我们的姓名与年龄
2.一个button,用来添加点击事件
3.一个表格table,六个标题
基本结构如代码所示:
<div class="boss">
<p>姓名:<input type="text" /></p>
<p>年龄:<input type="text" /></p>
<p>性别:<input type="text" /></p>
<p>学号:<input type="text" /></p>
<button class="btn">添加</button>
</div>
<table class="box" border="" cellspacing="0" cellpadding="0">
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>学号</th>
<th>操作</th>
</tr>
</table>
二丶给表单添加css样式
<style>
.boss {
width: 400px;
height: 500px;
text-align: center;
float: left;
font-size: 30px;
}
.boss input {
width: 60%;
height: 50px;
font-size: 30px;
}
.box {
width: 50%;
float: right;
text-align: center;
}
.btn {
width: 200px;
height: 40px;
font-size: 20px;
border-radius: 10px;
}
</style>
三、js代码:
<script>
var inp = document.querySelectorAll("input");
var btn = document.querySelector(".btn");
var box = document.querySelector(".box");
var arr = [];
var num = 1;
// 添加
btn.onclick = function() {
var strDemo = {
name: inp[0].value,
age: inp[1].value,
sex: inp[2].value,
id: inp[3].value
}
for (var i = 0; i < inp.length; i++) {
if (inp[i].value == "" || inp[i].value == null || inp[i].value == undefined) {
alert("请完善内容!");
return false;
}
}
if (arr.length > 0) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].id == strDemo.id) {
alert("学号不能重复!");
return false;
}
}
arr.push(strDemo);
} else {
arr.push(strDemo);
}
var trs = document.createElement("tr");
box.appendChild(trs);
var xh = document.createElement("td");
xh.innerHTML = num++;
trs.appendChild(xh);
for (var i = 0; i < inp.length; i++) {
var tds = document.createElement("td");
tds.innerHTML = inp[i].value;
trs.appendChild(tds);
}
var del = document.createElement("td");
del.innerHTML = "<button onclick='dels()'>删除</button>";
trs.appendChild(del);
var del = document.createElement("td");
del.innerHTML = "<button class='btn1' onclick='edit()'>编辑</button>";
trs.appendChild(del);
}
px();
// 删除
function dels(e) {
var faIndex = event.target.parentNode.parentNode;
for (var i = 0; i < arr.length; i++) {
if (arr[i].id == faIndex.children[4].innerHTML) {
faIndex.remove();
arr.splice(i, 1);
}
px();
}
console.log(arr);
}
// 排序
function px() {
var trs = document.querySelectorAll("tr");
for (var i = 1; i < trs.length; i++) {
trs[i].children[0].innerHTML = i;
console.log(trs[i]);
}
}
</script>