表格的添加、删除、全选、全不选、反选
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>表格案例</title> 6 <style type="text/css"> 7 * { 8 text-align: center; 9 } 10 11 h3 { 12 margin: 10px auto; 13 } 14 15 table { 16 margin: 20px auto; 17 width: 500px; 18 } 19 20 </style> 21 22 <script> 23 window.onload = function () { 24 //添加 25 var trs = document.getElementsByTagName("tr");//返回带有指定名称的所有元素 26 document.getElementById("addName").onclick = function () { 27 var name = document.getElementById("name").value; 28 document.getElementById("table").innerHTML += "<tr> " + 29 " <td><input type="checkbox" name="cb"/></td> " + 30 " <td>" + name + "</td> " + 31 " <td><a href="javascript:void(0);" onclick='this.parentNode.parentNode.remove();'>删除</a></td> " + 32 " </tr>"; 33 } 34 //javascript:void(0)去掉a标签的功能 35 //全选 36 document.getElementById("btn1").onclick = function () { 37 var cbs = document.getElementsByName("cb");//通过name获取元素返回是一个数组 38 for (var i = 0; i < cbs.length; i++) { 39 cbs[i].checked = true; 40 } 41 } 42 //全不选 43 document.getElementById("btn2").onclick = function () { 44 var cbs = document.getElementsByName("cb"); 45 for (var i = 0; i < cbs.length; i++) { 46 cbs[i].checked = false; 47 } 48 } 49 //反选 50 document.getElementById("btn3").onclick = function () { 51 var cbs = document.getElementsByName("cb"); 52 for (var i = 0; i < cbs.length; i++) { 53 cbs[i].checked = !cbs[i].checked; 54 } 55 } 56 } 57 </script> 58 </head> 59 <body> 60 <h3>表格案例</h3> 61 姓名:<input type="text" id="name"/> 62 <input type="button" value="添加" id="addName"/> 63 64 <table border="1" id="table"> 65 <tr> 66 <th>选择</th> 67 <th>姓名</th> 68 <th>操作</th> 69 </tr> 70 <tr> 71 <td><input type="checkbox" name="cb"/></td> 72 <td>武松</td> 73 <td><a href="javascript:void(0);" onclick="this.parentNode.parentNode.remove();">删除</a></td> 74 </tr> 75 <tr> 76 <td><input type="checkbox" name="cb"/></td> 77 <td>鲁智深</td> 78 <td><a href="javascript:void(0);" onclick="this.parentNode.parentNode.remove();">删除</a></td> 79 </tr> 80 <tr> 81 <td><input type="checkbox" name="cb"/></td> 82 <td>宋江</td> 83 <td><a href="javascript:void(0);" onclick="this.parentNode.parentNode.remove();">删除</a></td> 84 </tr> 85 <tr> 86 <td><input type="checkbox" name="cb"/></td> 87 <td>吴用</td> 88 <td><a href="javascript:void(0);" onclick="this.parentNode.parentNode.remove();">删除</a></td> 89 </tr> 90 <tr> 91 <td><input type="checkbox" name="cb"/></td> 92 <td>周聪</td> 93 <td><a href="javascript:void(0);" onclick="this.parentNode.parentNode.remove();">删除</a></td> 94 </tr> 95 <tr> 96 <td><input type="checkbox" name="cb"/></td> 97 <td>燕青</td> 98 <td><a href="javascript:void(0); " onclick="this.parentNode.parentNode.remove();">删除</a></td> 99 </tr> 100 </table> 101 <input type="button" value="全选" id="btn1"/> 102 <input type="button" value="全不选" id="btn2"/> 103 <input type="button" value="反选" id="btn3"/> 104 </body> 105 </html>