运用javascript实现表格的增加,删除和修改,实现结果如下:
表格可实现checkbox实现全选,实现数据新增,删除和修改等功能,当点击修改可将此条数据的数值附于编辑栏进行修改~~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>增删改</title>
<script type="text/javascript">
function $(name) {
return document.getElementById(name);
}
function $v(name) {
var obj = document.getElementById(name);
return obj.value;
}
function getItem(obj) {
return obj.value;
}
function show(sh) {
var tab = $("tab");
var name = $v("name");
var age = $v("age");
var home = $v("home");
var row1 = tab.rows[sh+1].cells[1];
var row2 = tab.rows[sh+1].cells[2];
var row3 = tab.rows[sh+1].cells[3];
$("name").value = row1.innerText;
$("age").value = row2.innerText;
$("home").value = row3.innerText;
}
function up() {
delRw();
var tab = $("tab");
var name = $v("name");
var age = $v("age");
var home = $v("home");
var row = tab.insertRow();
var idx = tab.rows.length - 2;
var r1 = row.insertCell(0);
var r2 = row.insertCell(1);
var r3 = row.insertCell(2);
var r4 = row.insertCell(3);
r1.innerHTML = "<input type='checkbox' value='" + idx + "' id='ch" + idx + "' οnchange='show("+idx+")' name='input' >";
r2.innerText = name;
r3.innerText = age;
r4.innerText = home;
return;
}
function addOne() {
var tab = $("tab");
var name = $v("name");
var age = $v("age");
var home = $v("home");
var row = tab.insertRow();
var idx = tab.rows.length - 2;
var r1 = row.insertCell(0);
var r2 = row.insertCell(1);
var r3 = row.insertCell(2);
var r4 = row.insertCell(3);
r1.innerHTML = "<input type='checkbox' value='" + idx + "' id='ch" + idx + "' οnchange='show("+idx+")' name='input' >";
r2.innerText = name;
r3.innerText = age;
r4.innerText = home;
return;
}
function checkAll() {
var all = $("all");
var tab = $("tab");
for (var i = 1; i <= tab.rows.length - 2; i++) {
var one1 = $("ch" + i);
if (all.checked == true) {
one1.checked = true;
} else {
one1.checked = false;
}
}
}
function delRw() {
var tab = $("tab");
for (var i = tab.rows.length - 1; i > 0; i--) {
if (tab.rows[i].cells[0].getElementsByTagName("input")[0].checked==true) {
tab.deleteRow(i);
}
}
}
</script>
</head>
<body>
<form>
<div style="margin-left: 100px;margin-top: 20px">
<input id="add" type="button" value="增加" style="border-radius: 5px" οnclick="addOne()">
<input id="del" type="button" value="删除" style="border-radius: 5px" οnclick="delRw()">
<input id="update" type="button" value="修改" style="border-radius: 5px" οnclick="up()">
</div>
<table id="tab" border="1" style="margin-top: 20px">
<tr>
<td>
<input id="all" type="checkbox" οnclick="checkAll()">
</td>
<td>姓名</td>
<td>年龄</td>
<td>住址</td>
</tr>
<tr>
<td>
</td>
<td>
<input id="name" type="text" style="border: hidden">
</td>
<td>
<input id="age" type="text" style="border: hidden">
</td>
<td>
<select id="home" style="width: auto;height: auto" οnchange="getItem(this)">
<option>---请选择---</option>
<option>烟台市</option>
<option>青岛市</option>
<option>济南市</option>
</select>
</td>
</tr>
</table>
</form>
</body>
</html>