<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> * { padding: 0; margin: 0; } .wrap { width: 300px; margin: 100px auto 0; } table { border-collapse: collapse; border-spacing: 0; border: 1px solid #c0c0c0; width: 300px; } th, td { border: 1px solid #d0d0d0; color: #404060; padding: 10px; } th { background-color: #09c; font: bold 16px "微软雅黑"; color: #fff; } td { font: 14px "微软雅黑"; } tbody tr { background-color: #f0f0f0; } tbody tr:hover { cursor: pointer; background-color: #fafafa; } </style> </head> <body> <div class="wrap"> <table> <thead> <tr> <th> <input type="checkbox" id="j_cbAll" /> </th> <th>菜名</th> <th>饭店</th> </tr> </thead> <tbody id="j_tb"> <tr> <td> <input type="checkbox" /> </td> <td>红烧肉</td> <td>田老师</td> </tr> <tr> <td> <input type="checkbox" /> </td> <td>西红柿鸡蛋</td> <td>田老师</td> </tr> <tr> <td> <input type="checkbox" /> </td> <td>油炸榴莲</td> <td>田老师</td> </tr> <tr> <td> <input type="checkbox" /> </td> <td>清蒸助教</td> <td>田老师</td> </tr> </tbody> </table> </div> <script src="common.js"></script> <script> //获取全选复选框 var th = my$("j_cbAll"); //获取单选的复选框 var tb = my$("j_tb").getElementsByTagName("input"); //为全选复选框添加点击事件 th.onclick = function() { //对单选的复选框进行遍历 for (var i = 0; i < tb.length; i++) { //每个单选框的状态跟复选框的一样————实现全选和全部不选 tb[i].checked = this.checked; } }; //为单选框添加点击事件 //对每一个单选框添加点击事件 for (var j = 0; j < tb.length; j++) { //添加点击事件 tb[j].onclick = function() { //默认都被选中了 var flag = true; //判断是不是全选 for (k = 0; k < tb.length; k++) { if (!tb[k].checked) { //没选中就进来了 flag = false; break; } } //全选的这个复选框的状态就是flag这个变量的值 th.checked = flag; }; } </script> </body> </html>
效果: