2016-12-05 53 views
0

的长度,我不想再重复jQuery的接受检查列表,而不是检查列表和复选框

jQuery("#checkboxList input:checkbox:checked").length 
jQuery("#checkboxList input:checkbox:checked") 
jQuery("#checkboxList input:checkbox:not(:checked)") 

我希望有一个更优雅的solution.Where我只能通过checkednot checkedlength PARAMS获得预期的结果。就像这样:

var checkboxList = jQuery("#checkboxList input:checkbox"); 
checkboxList.get(":checked") 
checkboxList.get(":not(:checked)") 
checkboxList.get(":checked").length 
<div id="checkboxList"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
    <input type="checkbox"> 
</div> 

回答

3

正确的方法使用的是filter(),不get()

var $checkboxes = $("#checkboxList input:checkbox"); 
 
var $checked = $checkboxes.filter(':checked') 
 
var $unchecked = $checkboxes.filter(':not(:checked)'); 
 

 
console.log('checked', $checked.length); 
 
console.log('unchecked', $unchecked.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="checkboxList"> 
 
    <input type="checkbox"> 
 
    <input type="checkbox" checked="checked"> 
 
    <input type="checkbox"> 
 
    <input type="checkbox" checked="checked"> 
 
    <input type="checkbox"> 
 
    <input type="checkbox" checked="checked"> 
 
    <input type="checkbox"> 
 
    <input type="checkbox" checked="checked"> 
 
    <input type="checkbox"> 
 
    <input type="checkbox" checked="checked"> 
 
    <input type="checkbox"> 
 
    <input type="checkbox" checked="checked"> 
 
    <input type="checkbox"> 
 
    <input type="checkbox" checked="checked"> 
 
    <input type="checkbox"> 
 
</div>

还要指出的是未经检查的数量可从减去来确定从复选框总数中检查的数量。为了完整起见,我只是在这里陈述了两个filter()陈述。