<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>复选框的全选、反选</title> <meta name="keywords" content="" /> <meta name="description" content="" /> <script type="text/javascript" src="../jquery-1.8.2.js"></script> <script type="text/javascript"> $(function(){ /* * 功能:实现复选框背景变色 */ //var cBoxSlaves = $('input[id^="cBoxId"]'); //各个分被控复选框对象Id var cBoxSlaves = $('input[name="arrName[]"]'); //各个分被控复选框对象Name //下面控制选中变色 cBoxSlaves.click(function(){ if($(this).attr('checked')=='checked'){ $(this).parent().parent().css('background','#ccccff'); //设置背景色 }else{ $(this).parent().parent().css('background',''); //更改背景色 } }); }); /* * 功能:实现全选、全不选、反选控件 * 参数:masterObj 总控件对象 * action 动作:1全选;0反选; */ function cBoxMulti(masterObj,action){ var cBoxMaster = $(masterObj); //总控件对象 //var cBoxSlaves = $('input[id^="cBoxId"]'); //各个分被控复选框对象Id var cBoxSlaves = $('input[name="arrName[]"]'); //各个分被控复选框对象Name if(action==1){ //全选/全不选 if(cBoxMaster.attr('checked')=='checked'){ cBoxSlaves.attr('checked',true); cBoxSlaves.parent().parent().css('background','#ccccff'); //设置背景色 }else{ cBoxSlaves.attr('checked',false); cBoxSlaves.parent().parent().css('background',''); //更改背景色 } }else if(action==0){ //反选 cBoxSlaves.each(function(){ //遍历分控件s,使其反选 if($(this).attr('checked')=='checked'){ $(this).attr('checked',false); $(this).parent().parent().css('background',''); //更改背景色 }else{ $(this).attr('checked',true); $(this).parent().parent().css('background','#ccccff'); //设置背景色 } }); } } </script> </head> <body> <table border="1" width="100%" cellspacing="0" cellpadding="0"> <form action="" method="post"> <tr> <th>复选</th> <th>Header2</th> </tr> <tr> <td><input type="checkbox" id="cBoxId1" name="arrName[]" value="1" /></td> <td>data1_2</td> </tr> <tr> <td><input type="checkbox" id="cBoxId2" name="arrName[]" value="2" /></td> <td>data1_2</td> </tr> <tr> <td><input type="checkbox" id="cBoxId3" name="arrName[]" value="3" /></td> <td>data1_2</td> </tr> <tr> <td><input type="checkbox" id="cBoxId4" name="arrName[]" value="4" /></td> <td>data1_2</td> </tr> <tr> <td><input type="checkbox" id="cBoxId5" name="arrName[]" value="5" /></td> <td>data1_2</td> </tr> <tr> <td> <input type="checkbox" onclick="cBoxMulti(this,1)" />全选 <input type="checkbox" onclick="cBoxMulti(this,0)" />反选 </td> <td>data1_2</td> </tr> </form> </table> </body> </html>