全選功能的實現(相容ie8,可以部分禁用)
阿新 • • 發佈:2018-11-06
注:
1.引數兩個,第一個引數為全選按鈕的選擇器,第二個引數為除全選按鈕外的其他複選框的父元素的選擇器,如果其父元素為table,選擇器要寫為 "table tbody"。
2.可有部分按鈕禁用(disabled),例如
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <div> <input type="checkbox" class="allChecked"/> 全選 </div> <ul class="asdf"> <li> <input type="checkbox"/> </li> <li> <input type="checkbox"/> </li> <li> <input type="checkbox" disabled/> </li> <li> <input type="checkbox"/> </li> <li> <input type="checkbox"/> </li> </ul> </body> <script src="jquery-1.8.3.min.js"></script> <script> /** * 全選功能 * @param * allClass 全選按鈕選擇器 * tableClass 包含除全選按鈕之外多有複選框的父元素選擇器 */ function allChecked(allClass, tableClass) { tableStr = tableClass; tableStr += " input[type=checkbox]"; notTableStr = tableClass; notTableStr += " input[type=checkbox][disabled]"; checkedStr = tableClass; checkedStr += " input[type=checkbox]:checked"; $(allClass).unbind("click"); $(allClass).prop("checked", false); $(allClass).bind("click",function() { var status = this.checked; $(tableStr).not(notTableStr).each(function(i, dom){ $(dom).prop("checked", status); }); }); $(tableStr).not(notTableStr).click(function() { if($(allClass).is(":checked") && !$(this).is(":checked")) { $(allClass).prop("checked",false); } var allLength = $(tableStr).not(notTableStr).length; if($(checkedStr).length == allLength) { $(allClass).prop("checked", true); } }); } allChecked(".allChecked", ".asdf"); </script> </html>