描述:实现对表格数据插入,删除,搜索,排序功能(其实这些表格数据应该是后台传到前台的,我们这里只是为了练习做逻辑操作)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<input type="text" value="wy" id="name"/><input type="text" value="年龄" id="age"/><input type="button" value="添加" id="add"/><br><br>
<input type="text" value="wy123" id="name1"/><input type="button" value="查询" id="search"/> <input type="button" value="排序" id="paixu"/><br><br>
<table border="1" id="tab">
<thead>
<td>id</td>
<td>姓名</td>
<td>年龄</td>
<td>操作</td>
</thead>
<tbody>
<tr>
<td>2</td>
<td>悠哈121</td>
<td>12</td>
<td><a href="javascript:;">删除</a></td>
</tr>
<tr>
<td>1</td>
<td>悠哈122</td>
<td>13</td>
<td><a href="javascript:;">删除</a></td>
</tr>
<tr>
<td>3</td>
<td>wy123</td>
<td>14</td>
<td><a href="javascript:;">删除</a></td>
</tr>
<tr>
<td>4</td>
<td>wy</td>
<td>15</td>
<td><a href="javascript:;">删除</a></td>
</tr>
</tbody>
</table>
<script>
/*添加*/
var add = document.getElementById('add');
var tbody = document.getElementById('tab').tBodies[0]
var countId = tbody.rows.length;
add.onclick = function(){
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
var a = document.createElement('a');
a.href='javascript:;'
a.innerHTML='删除';
countId++;
var tr = document.createElement('tr');
var tdid = document.createElement('td');
var tdname= document.createElement('td');
var tdage= document.createElement('td');
var tddel= document.createElement('td');
tdid.innerHTML=countId+'';
tdname.innerHTML=name;
tdage.innerHTML=age;
tddel.appendChild(a);
tr.appendChild(tdid);
tr.appendChild(tdname);
tr.appendChild(tdage);
tr.appendChild(tddel);
tbody.appendChild(tr)
}
/*忽略大小写模糊查询*/
var search = document.getElementById('search');
search.onclick = function(){
var name = document.getElementById('name1').value;
for(var i = 0; i < countId; i++){
if(name.toLowerCase() == tbody.rows[i].cells[1].innerHTML.toLowerCase()){
tbody.rows[i].style.background="yellow";
}else{
tbody.rows[i].style.background="";
}
}
}
/*删除*/
var adel = document.getElementsByTagName('a');
for(var i = 0; i< adel.length; i++){
adel[i].onclick = function(){
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode)
}
}
/*排序*/
paixu.onclick = function(){
var paixu = document.getElementById('paixu');
var arr = [];
function compare(arr1,arr2) {
return parseInt(arr1.cells[0].innerHTML)-parseInt(arr2.cells[0].innerHTML);
}
for(var i = 0; i < tbody.rows.length; i++){
arr.push(tbody.rows[i]);
}
arr.sort(compare);
for(var i = 0; i < tbody.rows.length;i++){
tbody.appendChild(arr[i]);
}
}
</script>
</body>
</html>
image.png
网友评论