里面除了实现了复选框的全选、全不选以及反选功能之外,还有对节点的创建、插入等功能。
实现效果:
效果动图JS代码
<script type="text/javascript">
var n = 2;
//添加
function add() {
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
var department = document.getElementById("department").value;
var choose = document.createElement("input");
choose.setAttribute("type", "checkbox");
choose.setAttribute("name", "choice");
choose.setAttribute("id", "p" + n);
n++;
var a = document.createElement("a");
a.innerHTML = "删除";
a.setAttribute("href", "#");
a.setAttribute("onclick", "del(this)");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("td");
var td4 = document.createElement("td");
var td5 = document.createElement("td");
td1.appendChild(choose)
td2.innerHTML = name;
td3.innerHTML = age;
td4.innerHTML = department;
td5.appendChild(a);
var tr = document.createElement("tr");
tr.appendChild(td1)
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
tr.appendChild(td5);
var table = document.getElementById("table");
table.appendChild(tr);
}
//全选
function choose(val) {
var check_box = document.getElementsByName("choice");
for(var i = 0; i < check_box.length; i++) {
check_box[i].checked = true;
}
}
//不选
function no_choose(val) {
var check_box = document.getElementsByName("choice");
for(var i = 0; i < check_box.length; i++) {
check_box[i].checked = false;
}
}
//反选
function re_choose(val) {
var check_box = document.getElementsByName("choice");
for(var i = 0; i < check_box.length; i++) {
if(check_box[i].checked == true) {
check_box[i].checked = false;
} else {
check_box[i].checked = true;
}
}
}
function del(val) {
var flag = confirm("确定要删除?");
var tds = val.parentNode;
var trs = tds.parentNode;
var tas = trs.parentNode;
if(flag) {
tas.removeChild(trs);
}
}
</script>
HTML代码
姓名:<input type="text" id="name" /><br />
年龄:<input type="text" id="age" /><br />
部门:<input type="text" id="department" /><br />
<input type="button" value="添加" onclick="add()" />
<input type="button" value="全选" id="choo" onclick="choose(this)" />
<input type="button" value="不选" id="no_choo" onclick="no_choose(this)" />
<input type="button" value="反选" id="re_choo" onclick="re_choose(this)" />
<table border="1" id="table" cellpadding="0" cellspacing="0">
<tr>
<td>选择</td>
<td>姓名</td>
<td>年龄</td>
<td>部门</td>
<td>操作</td>
</tr>
<tr>
<td><input type="checkbox" name="choice" id="p1"></td>
<td>王一</td>
<td>18</td>
<td>教育部</td>
<td>
<a href="#" onclick="del(this)">删除</a>
</td>
</tr>
</table>
网友评论