<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Js操作表格-对表格TR的添加/删除/拷贝</title>
<style>
body { margin:0; padding:0; font-size:12px;}
table, td{ border-collapse:collapse; border:1px solid #ccc;}
td{ padding:10px;}
</style>
</head>
<body>
<input type="button" id="Refresh" value="刷新页面" />
<input type="button" id="Insert_row" value="添加TR" />
<input type="button" id="delRow" value="删除选择" />
<input type="button" id="copyRow" value="拷贝选择" />
<table id="myTable">
<tr>
<td><input type="checkbox" name="checkbox" /></td>
<td>11</td>
<td>11</td>
</tr>
<tr>
<td><input type="checkbox" name="checkbox" /></td>
<td>22</td>
<td>22</td>
</tr>
<tr>
<td><input type="checkbox" name="checkbox" /></td>
<td>33</td>
<td>33</td>
</tr>
<tr>
<td><input type="checkbox" name="checkbox" /></td>
<td>44</td>
<td>44</td>
</tr>
<tr>
<td><input type="checkbox" name="checkbox" /></td>
<td>55</td>
<td>55</td>
</tr>
</table>
<script>
// 鼠标移动改变背景,可以通过给每行绑定鼠标移上事件和鼠标移除事件来改变所在行背景色。
window.onload = function(){
bgColor();
}
function bgColor(){ var tbody = document.getElementById('myTable').lastChild;
trs = tbody.getElementsByTagName('tr');
for(var i =0;i<trs.length;i++){
trs[i].onmouseover = function(){
this.style.backgroundColor ="#f2de76";
}
trs[i].onmouseout = function(){
this.style.backgroundColor ="#fff";
}
}
}
var doc = document,
myTable = doc.getElementById("myTable"),
selectBox = myTable.getElementsByTagName("input");
//复制tr
doc.getElementById("copyRow").onclick = function(){
for(var i=0; i<selectBox.length; i++){
if(selectBox[i].checked){
var newTr = myTable.rows[i].cloneNode(true);
newTr.getElementsByTagName("input")[0].checked = false;
myTable.appendChild(newTr);
}
}
}
//删除tr
doc.getElementById("delRow").onclick = function(){
for(var i=selectBox.length-1; i>=0; i--){
if(selectBox[i].checked){
myTable.deleteRow(i);
}
}
}
//添加tr
doc.getElementById("Insert_row").onclick = function(){
var tr = doc.createElement("tr");
for(var i=0; i<3; i++){
var td = doc.createElement("td");
txt = doc.createTextNode("新增");
td.appendChild(txt);
tr.appendChild(td);
if(i==0){
td.innerHTML = "<input type='checkbox' name='checkbox' />"
}
}
myTable.appendChild(tr);
}
//刷新页面
doc.getElementById("Refresh").onclick = function(){
location.reload();
}
</script>
</body>
</html>
myTable = doc.getElementById("myTable"),改为
myTable = doc.getElementById("myTable").lastChild,
table和tr之间还有一层tbody
其次在复制和添加函数最后调用 bgColor(),来为新增的节点添加事件