html部分
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>动态表格的增删改查</title>
<link rel="stylesheet" type="text/css" href="newlife.css">
</head>
<body>
<div id="continer">
<input type="text" id="keyword"></input>
<input type="button" value="搜索" id="sousuo"></input>
<table id="table1">
<thead>
<tr>
<th>编号</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
</thead>
<tbody id="body1"></tbody>
</table>
<div id="newadd">
<p class="p-2">年龄:<input type="text" placeholder="请输入年龄" id="age1"></p>
<p class="p-3">性别:<input type="text" placeholder="请输入性别" id="sex1"></p>
<p>
<input type="button" value="确认" id="queren">
</p>
</div>
</div>
<script src="rumen.js" type="text/javascript"></script>
</body>
</html>
css部分
tr,th{
border: 1px black solid;
height: 20px;
width: 120px;
}
tr,td{
border: 1px black solid;
height: 20px;
width: 120px;
}
#table1{
border-collapse: collapse;
margin-top: 30px;
}
#continer{
margin-left: 420px;
margin-top: 150px;
}
js部分
var array=[]
array.push({
num:1,
age:'1',
sex:'女',
isDelete:false
})
function render(list){
var arr=[]
for(var i = 0, len=list.length; i<len; i++){
if(!list[i].isDelete){ //如果没有被删除
arr.push('<tr><td>'+list[i].num+'</td><td>'+list[i].age+'</td><td>'+list[i].sex+'</td><td> <input class="delete" id="delete_'+list[i].num+'" type="button" value="删除"> <input class="update" id="update_'+list[i].num+'" type="button" value="修改"></td></tr>');
}
}
document.querySelector("#body1").innerHTML = arr.join('');
}
render(array)
var i = 2
queren.onclick = function add(){
var num = i
var age = document.querySelector('#age1').value;
var sex = document.querySelector('#sex1').value;
array.push({
num:num,
age:age,
sex:sex
})
i++;
render(array)
}
sousuo.onclick=function search(){
var temp = []
var keyword = document.querySelector('#keyword').value;
for(var i = 0;i<array.length;i++){
if (array[i].age.indexOf(keyword) != -1){
temp.push(array[i])
}
}
render(temp)
}
document.querySelector('#body1').onclick = function(e){
var target = e.target
if(target.getAttribute('class') == 'delete'){
var sourceId = target.getAttribute('id')
var id = sourceId.split('_')[1]
for(var i = 0; i<array.length; i++){
if(array[i].num == id){
array[i].isDelete = true;
}
}
render(array)
}
if (target.getAttribute('class') == 'update'){
var sourceId = target.getAttribute('id')
var id = sourceId.split('_')[1]
for(var i = 0; i<array.length; i++){
if(array[i].num == id){
var sum = prompt("请输入修改后的内容","18-女")
array[i].num = sum.split('-')[0]
array[i].age = sum.split('-')[1]
array[i].sex = sum.split('-')[2]
}
}
if(sum != null && sum !=''){
render(array)
}
else
alert("输入格式错误!")
}
}
网友评论