本文主要利用了事件委托来进行表格编写
该表格的主要功能如下:
- 有录入功能(用户输入姓名、性别、年龄,点击添加按钮,数据自动录入表格)
- 有删除功能
(基本功能如上,如需其他功能和样式可根据需要添加即可...)
效果图:
代码如下:
<!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>使用事件委托来书写表格</title>
<style>
* {
padding: 0;
margin: 0;
}
.top {
width: 830px;
margin: 80px auto;
margin-bottom: 0px;
/* border: 1px solid; */
padding-left: 50px;
}
table {
width: 800px;
border-collapse: collapse;
border: 1px solid #ccc;
text-align: center;
font-size: 16px;
/* display: none; */
/* position: absolute;
top: 0;
left: 0; */
}
tr {
height: 40px;
width: 300px;
}
thead {
background: rgb(140, 108, 255);
}
td {
width: 300px;
border-bottom: 1px solid #ccc;
}
.footer {
width: 800px;
margin: 20px auto;
line-height: 30px;
text-align: center;
position: relative;
}
.footer td {
border: 1px solid #fff;
text-align: center;
}
.footer td:hover {
box-shadow: 0px 0px 26px 0px rgb(140, 108, 255);
}
.footer .delete {
width: 40px;
height: 24px;
color: #fff;
text-align: center;
font-weight: 800;
border: 1px solid rgb(114, 89, 206);
background-color: rgb(140, 108, 255);
}
.footer .delete:hover {
box-shadow: 0px 0px 26px 0px rgb(140, 108, 255);
}
div input:last-child {
width: 50px;
height: 30px;
font-weight: 800;
}
.footer tr td:last-child:hover {
box-shadow: none;
}
</style>
</head>
<body>
<!-- 2. 使用事件委托来书写表格【√】
·有录入功能(用户输入姓名、性别、年龄,点击添加按钮,数据自动录入表格)
·有删除功能 -->
<div class="top">
姓名:<input type="text" value="" class="username">
年龄:<input type="text" value="" class="userage">
性别:<input type="text" value="" class="usergender">
<input type="button" value="添加" class="keepBtn">
</div>
<div class="footer has">
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>删除</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
var nameInp = document.querySelector(".username")
var ageInp = document.querySelector(".userage")
var genderInp = document.querySelector(".usergender")
var btnInp = document.querySelector(".keepBtn")
var tbody = document.querySelector("tbody")
var arr = []
// 使用时间委托来实现添加功能
btnInp.addEventListener(
"click",
function (e) {
var tempStr = {}
tempStr.name = nameInp.value.trim()
tempStr.age = ageInp.value.trim()
tempStr.gender = ageInp.value.trim()
if (!tempStr.name || !tempStr.age || !tempStr.gender) {
alert("少侠,你确定不填点东西进去???")
return
}
arr.push(tempStr)
// 添加数据后 清空输入框
nameInp.value = ""
genderInp.value = ""
ageInp.value = ""
// 动态创建表格
var str = ""
arr.forEach(
function (e) {
str += `<tr>`
for (var key in e) {
str += `<td>${e[key]}</td>`
}
str += `<td><input type="button" value="删除" class="delete"></td></tr>`
tbody.innerHTML = str
}
)
}
)
// 实现删除单行表格
tbody.addEventListener(
"click",
function (e) {
if(e.target.nodeName === "INPUT"){
e.target.parentNode.parentNode.remove()
}
}
)
</script>
</body>
</html>