checkbox全选/全不选,子复选框全选父复选框选中

<input type="checkbox" class="optionListAll">/* 父复选框 */
<input type="checkbox" name="optionList">
<input type="checkbox" name="optionList">
<input type="checkbox" name="optionList">
<input type="checkbox" name="optionList">
<input type="checkbox" name="optionList">
<input type="checkbox" name="optionList">
<input type="checkbox" name="optionList">
var optionListAll = $('.optionListAll');
var allList= $('[name="optionList"]');
var listLength = allList.length; // 父复选框全选/全不选 optionListAll.on("click", function() { var self = $(this); var state = self.prop('checked'); allList.each(function() {
    var that = $(this); state ? that.prop('checked', true) : that.prop('checked', false); // 判断父复选框是否选中,选中则子复选框全部选中 }) }); //子复选框 allList.each(function() {   var that = $(this); that.on('click', function () {     var selectedListLength = $('[name="optionList"]:checked'); // 选中的长度     for(var i = 0; i < listLength; i++) {       if(!allList[i].checked) { // 子复选框有一个没选择,父复选框不选         optionListAll.prop('checked', false); } } if( selectedListLength.length === listLength) { // 子复选框都选择,复选框选中
      optionListAll.prop('checked', true); } });
原文地址:https://www.cnblogs.com/duanfuying/p/8287359.html