使用 Jquery 检查多个复选框

Checking Multiple checkboxes using Jquery

在我的应用程序中,我使用一个复选框来 'Select All' 其他复选框。下面是我的代码片段,适用于我。但是我需要一个更短的方法来减少我的代码行。

$('#CheckAll').change(function(){   
                if ($(this).is(":checked")) {                                       
                    $('.checkboxes').each(function(){                                   
                        $(this).prop("checked", true);                      
                    });
                }
                else{               
                    $('.checkboxes').each(function(){                                   
                        $(this).prop("checked", false);                                                 
                    });             
                }               
            });

使用 "Ternary Operator" 是否有更简单的方法来实现此目的?

试试这个demo

$("#CheckAll").click(function(){
    $('input:checkbox').not(this).prop('checked', this.checked);
});

如果您真的想要使用三元运算符(fiddle):

$('#CheckAll').change(function () {
    ($(this).is(":checked") ? $('.checkboxes').prop("checked", true) :    $('.checkboxes').prop("checked", false))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' id='CheckAll'> Check all
<br><br>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>


但是,您可以使用 select 或 (un)select 复选框使其更短:

$('#CheckAll').change(function() {
  if ($(this).is(":checked")) {
    $('.checkboxes').prop("checked", true);
  } else {
    $('.checkboxes').prop("checked", false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' id='CheckAll'>Check all
<br>
<br>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>
<input type='checkbox' class='checkboxes'>

使用这个:

   $('#CheckAll').change(function(){   
                    if ($(this).is(":checked")) {                                       
                        $('.checkboxes').prop("checked", true);                      

                    }
                    else{               
                        $('.checkboxes').prop("checked", false);                                                        
                    }               
                });

试试这个:

  var chks = $('.checkboxes'); // cache all once
  $('#CheckAll').change(function(e) {
    chks.prop('checked', this.checked);
  });
$('#CheckAll').change(function(){
    $('.checkboxes').prop("checked",$(this).prop("checked"));
});