使用icheck选中所有复选框

use*_*653 5 checkbox jquery icheck

我正在使用iCheck插件进行复选框.我在那里放了一个"全选"功能.结构:

  • 全选
  • 复选框1
  • 复选框2
  • 复选框3

它工作正常,如检查"全选",将选中所有复选框.取消选中"全选"时,将取消选中所有复选框.但是,在选中"全选"后,如果取消选中任何复选框,则应自动取消选中"全选",因为此时未选中所有复选框.

为此,我写了这个:

$('#check-all').on('ifChanged', function(event){
    if($('.check').filter(':checked').length == $('.check').length) {
        $('#check-all').iCheck('check');
    } else {
        $('#check-all').iCheck('uncheck');
    }
    $('#check-all').iCheck('update');
});
Run Code Online (Sandbox Code Playgroud)

但是,在输入此代码后,我的复选框工作不正常,如"全部选择"不能单击,它需要经常多次点击.如果取消选中任何一个复选框,也不会取消选中"全选".代码有什么问题?如何正确写?

小提琴工作

har*_*una 15

// Remove the checked state from "All" if any checkbox is unchecked
$('.check').on('ifUnchecked', function (event) {
    $('#check-all').iCheck('uncheck');
});

// Make "All" checked if all checkboxes are checked
$('.check').on('ifChecked', function (event) {
    if ($('.check').filter(':checked').length == $('.check').length) {
        $('#check-all').iCheck('check');
    }
});
Run Code Online (Sandbox Code Playgroud)

处理$('#check-all').on('ifUnchecked', ...是棘手的 - 它触发其他处理,每个复选框都取消选中

小提琴