问题是因为您使用的是
map()
,这是
指数
,而不是第二个参数,第二个参数是对元素本身的引用:
var arr = $('#checklist-form input[type="checkbox"]').map(function(i, el) {
return $(el).is(':checked');
}).toArray();
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="checklist-form" action="">
<h1>this</h1>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="check-item0" required="" checked="true">
<label class="form-check-label" for="check-item0">
One
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="check-item1" required="">
<label class="form-check-label" for="check-item1">
Two
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="check-item2" required="">
<label class="form-check-label" for="check-item2">
Three
</label>
</div>
</form>
checked
属性直接从元素中删除并使用
get()
toArray()
要稍微提高逻辑的性能,请执行以下操作:
var arr = $('#checklist-form input[type="checkbox"]').map(function(i, el) {
return el.checked;
}).get();
甚至,正如@charlietfl所指出的,您可以消除对传递给处理函数的参数的依赖,并使用
this
处理程序函数中的关键字,在所提供元素的范围内调用:
var arr = $('#checklist-form input[type="checkbox"]').map(function() {
return this.checked;
}).get();