实训第三天笔记
用html和js实现一个简单的记录列表,包含添加、删除、修改和模糊搜索。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>记录表</title>
<script type="text/javascript">
var vInput = document.getElementsByTagName('input');
var id = 1;
function add() {
var vname = vInput[0].value;
var vage = vInput[1].value;
if (vname == '' || vage == '' || /\d+/.test(vname) || /\D+/.test(vage)) {
alert("请输入正确格式!");
return;
}
//id
var oTr = document.createElement("tr");//<tr></tr>
var oTd = document.createElement("td");//<td></td>
oTd.innerHTML = id++;//<td>1</td>
oTr.appendChild(oTd);//<tr><td>1</td></tr>
//姓名
oTd = document.createElement("td");
oTd.innerHTML = vname;
oTr.appendChild(oTd);
//年龄
oTd = document.createElement("td");
oTd.innerHTML = vage;
oTr.appendChild(oTd);
//操作
oTd = document.createElement("td");
oTd.innerHTML = "<a href='#'>删除</a> <a href='#'>修改</a>";
var atag = oTd.getElementsByTagName('a');
atag[0].onclick = testdelete;
atag[1].onclick = testupdate;
oTr.appendChild(oTd);
document.getElementById('tbody').appendChild(oTr);
}
function search() {
var tName = document.getElementsByTagName('input')[2].value;
var oTr = document.getElementsByTagName('tr');
for (var i = 1; i < oTr.length; i++) {
oTr[i].removeAttribute('style');
if (oTr[i].cells[1].innerHTML.indexOf(tName) > -1) {
oTr[i].style.backgroundColor = "red";
}
}
}
var testdelete = function() {
var temp = this.parentNode.parentNode;
temp.style.backgroundColor = "yellow";
if (confirm("是否删除此行?")) {
document.getElementById("tbody").removeChild(temp);
} else {
temp.removeAttribute("style");
}
};
var testupdate = function() {
var thistd = this.parentNode;//<td>
var tAge = thistd.previousSibling;
var tName = tAge.previousSibling;
var tId = tName.previousSibling.innerHTML;
tAge.innerHTML = "<input type='text' id='tAge"+tId+"' value='"+tAge.innerHTML+"'></input>"
tName.innerHTML = "<input type='text' id='tName"+tId+"' value='"+tName.innerHTML+"'></input>"
thistd.innerHTML = "<a href='javascript:;'>保存</a>";
thistd.getElementsByTagName("a")[0].onclick = function() {
tAge.innerHTML = document.getElementById("tAge" + tId).value;
tName.innerHTML = document.getElementById("tName" + tId).value;
thistd.innerHTML = "<a href='#'>删除</a> <a href='#'>修改</a>";
var atag = document.getElementsByTagName('a');
atag[0].onclick = testdelete;
atag[1].onclick = testupdate;
};
};
</script>
</head>
<body>
<div>
记录列表<br> <br> 姓名:<input type="text" placeholder="必填非数字">
年龄:<input type="text" placeholder="必填数字">
<button onclick="add()">添加</button>
<br> <br> 姓名:<input type="text" placeholder="姓名">
<button onclick="search()">搜索</button>
<br> <br>
<table style="border: 1px solid black; width: 600px;">
<thead>
<tr>
<th style="width: 15%; text-align: left">ID</th>
<th style="width: 30%; text-align: left">姓名</th>
<th style="width: 30%; text-align: left">年龄</th>
<th style="width: %15; text-align: left">操作</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
</div>
</body>
</html>
页面效果