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="每次都在标题下一行插入行" οnclick="test()" style="cursor:pointer;" type="button">
<input class="btn" name="_btn2" value="将除标题外的所有行替换成新内容" οnclick="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>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/38830.html