//样式
<style>
.top {
text-align: center;
}
.bot table {
margin: 30px auto;
width: 1003px;
border-collapse: collapse;
font-size: 14px;
text-align: center;
}
.bot table,
tr,
td,
th {
border: 1px solid #cecece;
}
.bot table,
tr:nth-child(1) {
background-color: #E0E8FB;
}
</style>
//布局结构
<div class="top">
<form class="inf" autocomplete="off" name="inf">
<label>姓名:<input type="text" class="name" name="name" value=""></label>
<label>年龄:<input type="text" class="age" name="age"></label>
<label>性别:<select class="sex" name="sex">
<option value="男">男</option>
<option value="女">女</option>
</select></label>
<label>薪资:<input type="text" class="pay" name="pay"></label>
<label>就业城市:<select class="city" name="city">
<option value="北京">北京</option>
<option value="上海">上海</option>
</select></label>
<button>录入</button>
</form>
</div>
<div class="bot">
<table>
<thead>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>薪资</th>
<th>就业城市</th>
<th>操作</th>
</thead>
<tbody>
</tbody>
</table>
</div>
//js实现功能
<script>
//获取元素
const inf = document.querySelector('.inf');
const arr = [];
const name = document.querySelector('.name');
const age = document.querySelector('.age');
const sex = document.querySelector('.sex');
const pay = document.querySelector('.pay');
const city = document.querySelector('.city');
const tbody = document.querySelector('tbody');
const items = document.querySelectorAll('.inf [name]');
inf.addEventListener('submit', function (e) {
e.preventDefault();
//非空判断
for (let i = 0; i < items.length; i++) {
if (items[i].value === '') {
return alert('数据不能为空');
}
}
//创建一个对象
let obj = {
nmu: arr.length + 1,
name: name.value,
age: age.value,
sex: sex.value,
pay: pay.value,
city: city.value
}
//把对象追加到数组
arr.push(obj);
//清空表单
this.reset();
//调用渲染页面
getApply()
})
//渲染页面
function getApply() {
//先清空tbody
tbody.innerHTML = ''
//循环遍历数组
for (let i = 0; i < arr.length; i++) {
//创建 n个tr
let tr = document.createElement('tr');
//tr里添加遍历的数据
tr.innerHTML = ` <tr>
<td>${i + 1}</td>
<td>${arr[i].name}</td>
<td>${arr[i].age}</td>
<td>${arr[i].sex}</td>
<td>${arr[i].pay}</td>
<td>${arr[i].city}</td>
<td><a data-i=${i}>删除</a></td>
</tr>`
//把tr添加到tbody里(如果里面还有tr,添加第一个tr后面)
tbody.appendChild(tr)
}
}
getApply()
//删除
tbody.addEventListener('click', function (e) {
if (e.target.tagName === 'A') {
arr.splice(e.target.dataset.id, 1)
getApply()
}
})
</script>