2016-12-05 71 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()陳述。