js 表格的增删操作,全选,反选,全不选操作
<!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>Document</title>
<style>
table,
tr,
td,
th {
border: 1px solid #000;
}
table {
width: 500px;
border-collapse: collapse;
text-align: center;
}
#module {
width: 100vw;
height: 100vh;
position: absolute;
z-index: 999;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.492);
display: none;
}
.user-add {
width: 300px;
margin: 200px auto;
}
.active {
background: green;
}
</style>
</head>
<body>
<table id="list">
<tbody></tbody>
</table>
<p>
<button onclick="addUserPage()">新增</button>
<button onclick="delUserHandle()">删除</button>
<button onclick="selectedHandle(2)">反选</button>
<button onclick="selectedHandle(1)">全不选</button>
<button onclick="selectedHandle(3)">全选</button>
</p>
<div id="module">
<div class="user-add">
信息1:<input type="text"><br><br>
信息2:<input type="text"><br><br>
信息3:<input type="text"><br><br>
信息4:<input type="text"><br><br>
<button onclick="addUserHandle()">新加</button>
</div>
</div>
<script>
var userList = [
{
status: true,
name: '小明',
age: 12,
sex: '男',
address: '北京'
},
{
status: false,
name: '小花',
age: 18,
sex: '女',
address: '北京'
},
{
status: false,
name: '小天',
age: 14,
sex: '男',
address: '北京'
}
]
var tbody = document.getElementsByTagName('tbody')[0]
fillData(userList)
function fillData(data) {
tbody.innerHTML = ''
for (var i = 0; i < data.length; i++) {
tbody.innerHTML += `<tr class="${data[i].status ? 'active' : ''}" οnclick="statusChange(${i})">
<td><input type="checkbox" ${data[i].status ? 'checked' : ''}></td>
<td>${data[i].name}</td>
<td>${data[i].age}</td>
<td>${data[i].sex}</td>
<td>${data[i].address}</td>
<td><a href="javascript:void(0);" οnmοusedοwn="delHandle(${i})">删除</a></td>
</tr>`
}
}
var module = document.getElementById('module')
function addUserPage() {
module.style.display = 'block'
}
var inputs = module.getElementsByTagName('input')
function addUserHandle() {
userList.push({
status: false,
name: inputs[0].value,
age: inputs[1].value,
sex: inputs[2].value,
address: inputs[3].value
})
fillData(userList)
module.style.display = 'none'
}
function delUserHandle() {
userList = userList.filter(function (el, index) { return el.status === false })
fillData(userList)
}
function statusChange(index) {
userList[index].status = !userList[index].status
fillData(userList)
}
function selectedHandle(type) {
for (var i = 0; i < userList.length; i++) {
userList[i].status = type === 1 ? false : type === 2 ? !userList[i].status : true
}
fillData(userList)
}
function delHandle(i) {
userList = userList.filter(function (el, index) { return index !== i })
fillData(userList)
}
</script>
</body>
</html>