js实现简单的全选和反选

js实现简单的全选和反选,一般都用得上。代码很简单,就这一小段。
  1. function DoCheck() {
  2.     var ch = document.getElementsByName("ids");
  3.     if (document.getElementById("allSelect").checked == true) {
  4.         for (var i = 0; i < ch.length; i++) {
  5.             ch[i].checked = true;
  6.         }
  7.     } else {
  8.         for (var i = 0; i < ch.length; i++) {
  9.             ch[i].checked = false;
  10.         }
  11.     }
  12. }
顺便把完整的测试代码贴出来
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>全选和反选演示</title>
  6.     <script type="text/javascript">
  7.         function DoCheck() {
  8.             var ch = document.getElementsByName("ids");
  9.             if (document.getElementById("allSelect").checked == true) {
  10.                 for (var i = 0; i < ch.length; i++) {
  11.                     ch[i].checked = true;
  12.                 }
  13.             } else {
  14.                 for (var i = 0; i < ch.length; i++) {
  15.                     ch[i].checked = false;
  16.                 }
  17.             }
  18.         }
  19.     </script>
  20. </head>
  21. <body>
  22.     <table border="1px solid #ccc">
  23.         <tr>
  24.             <td>
  25.                 <input type="checkbox" id="allSelect" onclick="javascript:DoCheck()">
  26.             </td>
  27.             <td>姓名</td>
  28.             <td>性别</td>
  29.             <td>年龄</td>
  30.             <td>职业</td>
  31.         </tr>
  32.         <tr>
  33.             <td>
  34.                 <input type="checkbox" name="ids">
  35.             </td>
  36.             <td>李白</td>
  37.             <td></td>
  38.             <td>28</td>
  39.             <td>诗人</td>
  40.         </tr>
  41.         <tr>
  42.             <td>
  43.                 <input type="checkbox" name="ids">
  44.             </td>
  45.             <td>周瑜</td>
  46.             <td></td>
  47.             <td>19</td>
  48.             <td>智将</td>
  49.         </tr>
  50.         <tr>
  51.             <td>
  52.                 <input type="checkbox" name="ids">
  53.             </td>
  54.             <td>杨玉环</td>
  55.             <td></td>
  56.             <td>25</td>
  57.             <td>贵妃</td>
  58.         </tr>
  59.     </table>
  60. </body>
  61. </html>
  本文链接:https://liuyanzhao.com/6042.html

发表评论

目前评论:2