运行效果:
源代码:
1 <!DOCTYPE html> 2 <html lang="zh"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>动态表格</title> 6 </head> 7 <body> 8 <button type="button" onclick="refresh()">刷新</button> 9 <button type="button" onclick="checkAll()">全选</button> 10 <button type="button" onclick="uncheckAll()">不选</button> 11 <button type="button" onclick="addCell()">添加</button> 12 <button type="button" onclick="copyCell()">拷贝</button> 13 <button type="button" onclick="copyCell();delCell()">移动</button> 14 <button type="button" onclick="delCell()">删除</button> 15 16 <table id="table1" border="1" width="320"> 17 <tr> 18 <td width="20"><input type="checkbox" /></td> 19 <td width="100">1</td> 20 <td width="100">1</td> 21 <td width="100">1</td> 22 </tr> 23 <tr> 24 <td><input type="checkbox"></td> 25 <td>2</td> 26 <td>2</td> 27 <td>2</td> 28 </tr> 29 </table> 30 <br /> 31 <table id="table2" border="1" width="320"> 32 <tr> 33 <td width="20"><input type="checkbox" /></td> 34 <td width="100">你好!</td> 35 <td width="100">你好!</td> 36 <td width="100">你好!</td> 37 </tr> 38 <tr> 39 <td><input type="checkbox" /></td> 40 <td>你坏!</td> 41 <td>你好!</td> 42 <td>你好!</td> 43 </tr> 44 </table> 45 <form name="frmRefresh" action="dynamic_table.html"> 46 </form> 47 48 <script type="text/javascript"> 49 function addCell(){ //添加新的单元格 50 //插入新的一行 51 var oTargetRow = document.all("table1").insertRow(); 52 for (var k = 0; k < document.getElementById("table1").rows[0].cells.length; k++) { 53 var oCell = oTargetRow.insertCell(); 54 if (parseInt(k) === 0) { 55 oCell.innerHTML = "<input type='checkbox'>"; 56 } 57 else { 58 oCell.innerHTML = k; 59 } 60 } 61 } 62 63 function checkAll(){ //选中所有的单元格 64 var eInput = document.all("table1").getElementsByTagName("input"); 65 for (var i = 0; i < eInput.length; i++) { 66 eInput[i].checked = true; 67 } 68 } 69 70 function uncheckAll() { 71 var eInput = document.all("table1").getElementsByTagName("input"); 72 for (var i = 0; i < eInput.length; i++) { 73 eInput[i].checked = false; 74 } 75 } 76 77 function copyCell(){ //拷贝单元格 78 var eInput = document.all("table1").getElementsByTagName("input"); 79 var oTargetRow = null; 80 for (var i = 0; i < eInput.length; i++) { 81 if (eInput[i].checked) { 82 var oSourceRow = eInput[i].parentElement.parentElement; 83 //插入新的一行 84 oTargetRow = document.all("table2").insertRow(); 85 for (var k = 0; k < document.all("table1").rows[0].cells.length; k++) { 86 var oCell = oTargetRow.insertCell(); 87 oCell.innerHTML = oSourceRow.cells[k].innerHTML; 88 } 89 } 90 } 91 } 92 93 function delCell(){//删除单元格 94 var eInput = document.all("table1").getElementsByTagName("input"); 95 for (var i = eInput.length - 1; i >= 0; i--) { 96 if (eInput[i].checked) { 97 var oSourceRow = eInput[i].parentElement.parentElement; 98 document.all("table1").deleteRow(oSourceRow.rowIndex); 99 } 100 } 101 } 102 103 function refresh(){ //刷新 104 frmRefresh.submit(); 105 } 106 107 </script> 108 </body> 109 </html>