js操作表格元素的添加删除实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#form {
width: 480px;
margin: 30px auto;
border: 1px solid #eee;
border-radius: 5px;
padding: 10px;
line-height: 30px;
position: relative;
}
button {
position: absolute;
right: 10px;
bottom: 10px;
}
#tab {
width: 500px;
margin: 30px auto;
border-collapse: collapse;
}
th,
td {
border: 1px solid #000;
padding: 5px;
}
tbody tr td:first-child {
text-align: center;
}
/*input[type] 属性选择器 选择input标签,并且有type属性input标签*/
/*input[type = "checkbox"] 选择有type属性并且值为checkbox的input标签*/
input[type="checkbox"] {
width: 15px;
height: 15px;
}
#div1 {
position: relative;
width: 480px;
padding: 10px;
margin: 0 auto;
}
</style>
<script type="text/javascript">
window.onload = function(){
//获取元素
var inpS = document.querySelectorAll('#form input');
var btnS = document.getElementsByTagName('button');
var tab = document.getElementById('tab');
var all = document.getElementById('all');
// console.log(tab,all)
//添加内容
btnS[0].onclick = function(){
//创建一行
var tr = document.createElement('tr');
for(var i=0; i<4; i++){
//向行内添加列
tr.appendChild(document.createElement('td'));
}
//获取伪数组tr内容的td
var tdS = tr.children;
tdS[0].innerHTML = '<input type="checkbox">';
tdS[1].innerText = inpS[0].value;
tdS[2].innerText = inpS[1].checked == true ? '男' : '女';
tdS[3].innerText = inpS[3].value;
//tr追加表格
tab.tBodies[0].appendChild(tr);
}
//全选按钮 和全选按钮的状态相同
all.onclick = function(){
//获取所有tbody中的复选框
var ck = tab.tBodies[0].getElementsByTagName('input');
for(var i=0; i<ck.length; i++){
ck[i].checked = all.checked;
}
}
//删除 选中的tr
btnS[1].onclick = function(){
//获得tbody中的复选框
var ck = tab.tBodies[0].getElementsByTagName('input');
//判断复选框状态
for(var i=0; i<ck.length; i++){
if(ck[i].checked == true){
//取得父级的父级 删除该行
ck[i].parentNode.parentNode.remove();
i--;
}
}
}
}
</script>
</head>
<body>
<div id="form">
请输入姓名: <input type="text" id="name"> <br>
请输入性别: <input type="radio" id="sex" name="sex" checked>男 <input type="radio" name="sex">女<br>
请输入年龄: <input type="text" id="age">
<button>添加到表格</button>
</div>
<table id="tab">
<thead>
<tr>
<th width="20%"><label><input type="checkbox" id="all">全选</label></th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>张三</td>
<td>女</td>
<td>88</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>李四</td>
<td>男</td>
<td>18</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>王五</td>
<td>女</td>
<td>1</td>
</tr>
</tbody>
</table>
<div id="div1">
<button>删除所选行</button>
</div>
</body>
</html>
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634787.html