表單處理時經常會有全選的功能,但是這個功能往往會被忽視一個細節,就是逐個選中 checkBox 直至全選時,經常會忘記修改全選 checkBox 的狀態,某知名互聯網公司的網盤就會出現這樣的問題,問題如圖:
所以,需要給 checkBox 的點擊事件做一下處理:點擊時遍歷一下除了全選的單選框之外的所有單選框,如果有未選中的,則全選不選中,如果全部都選中了,則修改全選框的狀態,以下是我寫的一個簡單的例子:
運行結果:
以下就是例子的全部代碼:
<!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="content-type" content="text/html; charset=GBK"/> <style> ul,li{ list-style:none; } </style> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript" charset="utf-8"> function clickAll(){ $(".checkOne").prop("checked",$(".checkAll").prop("checked")); } function clickOne(){ var allChecked = true; $(".checkOne").each(function(){ if($(this).prop("checked") == false){ allChecked = false; }; }); if(allChecked){ $(".checkAll").prop("checked",true); } else { $(".checkAll").prop("checked",false); } } </script> </head> <body> <ul> <li><input type="checkBox" class="checkAll" onclick="clickAll()" id="all"/><label for="all">愛好(全選)</label></li> <br/> <li><input type="checkBox" class="checkOne" onclick="clickOne()" id="ck1"/><label for="ck1">足球</label></li> <li><input type="checkBox" class="checkOne" onclick="clickOne()" id="ck2"/><label for="ck2">網球</label></li> <li><input type="checkBox" class="checkOne" onclick="clickOne()" id="ck3"/><label for="ck3">籃球</label></li> </ul> </body> </html>
一起學習,有問題歡迎拍磚吐槽……