<style>
* {
margin: 0;
padding: 0;
}
/* 设计大div */
.addBox {
width: 600px;
margin: 0 auto;
}
/* 设计表单 */
.addBox form {
width: 100%;
display: flex;
flex-direction: column;
}
/* 设计表格 */
table {
width: 600px;
margin: 0 auto;
text-align: center;
}
</style>
</head>
<body>
<div class="addBox">
<!-- 创建一个form表单 用来提交数据 -->
<form>
<!-- label定义标注 -->
<label>
<!-- input表单(搜集用户信息) -->
姓名: <input class="username" type="text">
</label>
<label>
性别: <input class="gender" type="text">
</label>
<label>
年龄: <input class="age" type="text">
</label>
<label>
班级: <input class="classRoom" type="text">
</label>
<!-- 表单按钮 -->
<button>添加</button>
</form>
</div>
<!-- 创建一个表格 -->
<table border="1" cellspacing='0'>
<!-- 定义表格的表头 -->
<thead>
<!-- 行 -->
<tr>
<!--th(表头单元格) -->
<th>ID</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>班级</th>
<th>操作</th>
</tr>
</thead>
<!-- 定义一个表格主体 -->
<tbody>
<tr>
<!-- td(标准单元) -->
<td>1</td>
<td>张思睿</td>
<td>男</td>
<td>18</td>
<td>2114</td>
<td>
<!-- 创建按钮 -->
<button>删除</button>
</td>
</tr>
</table>
<script>
//数据
var users = [
{ id: 1, name: 'Jack', age: 18, gender: '男', classRoom: '2114' },
{ id: 2, name: 'Rose', age: 20, gender: '女', classRoom: '2114' },
{ id: 3, name: 'Tom', age: 22, gender: '男', classRoom: '2114' }
]
// 动态渲染表格
// 获取显示在主体的元素
var tbodyBtn = document.querySelector('tbody')
// 获取form表单元素
var formBtn = document.querySelector('form')
// 获取姓名信息元素
var usernameBtn = document.querySelector('.username')
// 获取性别信息元素
var genderBtn = document.querySelector('.gender')
// 获取年龄信息元素
var ageBtn = document.querySelector('.age')
// 获取班级信息元素
var classRoomBtn = document.querySelector('.classRoom')
// 获取按钮
var btn = document.querySelector('button')
// 先调用一次为了打开就有数据
pack()
// 封装成一个函数方便使用
function pack() {
// 定义一个空字符串
var str = ``
// 循环遍历拿到每一项数据
users.forEach(function (item) {
// console.log(item);
// 将数据添加在相应的位置(模板字符串)
// 用${}来获取每一项的值 这里是键值对
str += `
<tr>
<td>${item.id}</td>
<td>${item.name} </td>
<td>${item.gender}</td>
<td>${item.age}</td>
<td>${item.classRoom}</td>
<td>
<button>删除</button>
</td>
</tr>
`
})
// 返回到标签内
tbodyBtn.innerHTML = str
}
// 给form表单添加submit事件
formBtn.onsubmit = function (e) {
// 1.事件处理兼容
e = e || window.event
// 2.阻止默认行为
try {
e.preventDefault()
} catch (arr) {
e.returnValue = false
}
// 3.获取用户输入信息
// .trim()去除字符串的头尾空格
var name = usernameBtn.value.trim()
var age = ageBtn.value.trim()
var gender = genderBtn.value.trim()
var classRoom = classRoomBtn.value.trim()
// 4.验证信息是否完整(非空验证)
/* (非空验证)!name
name = 1 true ! false 不弹窗
name = '' false ! true 弹窗
*/
if (!name || age === '' || gender === '' || classRoom === '')
return alert('请输入内容')
// 将用户输入的信息添加成一个对象
var obj = {
// users长度为0 fslse ! true 执行1
// users长度为1 true ! false 执行:后的
id: !users.length ? 1 : users[users.length - 1].id + 1,
name: name,
age: age,
gender: gender,
classRoom: classRoom
}
/* // 如何确定我们的id
if (users.length === 0) {
// 如果之前没有数
obj.id = 1
} else {
// 如果之前有数据
obj.id = users[users.length - 1].id + 1
} */
// 添加到数组中
users.push(obj)
// 调用函数 用新的数据渲染表格
pack()
}
</script>