您的位置:首页 > Web前端 > JavaScript

js Dom操作table添加行insertBefore

2015-10-09 10:10 417 查看
js操作表格,添加行。

1、始终在首行下面插入新行

2、将除了首行外的所有行删除并替换成新行

使用的知识点

js dom操作,创建元素createElement,设置元素属性setAttribute,添加子元素appendChild,新元素插入已知元素之前insertBefore,获取元素父元素parentNode

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>测试</title>
<style>
@-moz-document url-prefix()
{
.tb-x1{margin-left:1px;}
}
.tb-x1 table{border-collapse:collapse;}
.tb-x1 th{background:#D0E1F5;border:1px solid #ccc;padding:5px;}
.tb-x1 td{background:#fff;border:1px solid #ccc;padding:4px 5px;text-align:center;}
.tb-x0 th,.tb-x0 td{padding:5px;}

.btn{background:url(i/btn.gif) -188px -31px;border:none;width:299px;height:27px;color:#053ea6;margin-left:5px;font-weight:bold;position:relative;top:3px}
</style>
</head> <body id="mainframe">
<div id="content">
<div class="tb-x1 resultlist">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody><tr id="head">
<th width="5%"></th>
<th width="20%">名称</th>
<th width="10%">所在城市</th>
<th width="20%">地址</th>
<th width="10%">电话</th>
<th width="10%">状态</th>
<th width="10%">操作</th>
</tr>
<tr id="noneRecord">
<td colspan="8">暂无记录</td>
</tr>
</tbody></table>
</div>
<div class="tb-x0">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody><tr>
<td align="center" width="120">
<input class="btn" name="_btn1" value="每次都在标题下一行插入行" onclick="test()" style="cursor:pointer;" type="button">
<input class="btn" name="_btn2" value="将除标题外的所有行替换成新内容" onclick="test2()" style="cursor:pointer;" type="button">
</td>
</tr>
</tbody></table>
</div>
</div>

<script language="javascript">
function createNoneRecordTr(){
var td = document.createElement("td");
td.setAttribute("colspan",8);
td.innerHTML="暂无记录"+Math.random();
var tr = document.createElement("tr");
tr.setAttribute("id","noneRecord");
tr.appendChild(td);
return tr;
}
function test(){
var headTr = document.getElementById("head");
var table = headTr.parentNode;
var noneRecordTr = createNoneRecordTr();
table.insertBefore(noneRecordTr, headTr.nextElementSibling);
}
function test2(){
var headTr = document.getElementById("head");
var table = headTr.parentNode;
var noneRecordTr = createNoneRecordTr();
var nextEl = headTr.nextElementSibling;
while(nextEl != null){
table.removeChild(nextEl);
nextEl = headTr.nextElementSibling;
}
table.appendChild(noneRecordTr);
}
</script>
</body></html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: