我有这个代码
var selected = new Array();
$(".client_associates_users input:checked").each(function(index) {
selected.push($(this).val());
});
Run Code Online (Sandbox Code Playgroud)
它工作得很好,但我想知道jQuery是否有一个收集,所以我不必创建一个数组并推动它.
我基本上想要检查输入字段的所有值
是的,$.fn.map http://api.jquery.com/map/或$.map http://api.jquery.com/jQuery.map/
var $checkboxes = $(".client_associates_users input:checked"),
selected = $checkboxes.map(function(i){
return $checkboxes.eq(i).val();
}).get();
Run Code Online (Sandbox Code Playgroud)
或者这个$.map(我更喜欢这个)
var $checkboxes = $(".client_associates_users input:checked"),
selected = $.map($checkboxes, function(el,i){
return $checkboxes.eq(i).val();
});
Run Code Online (Sandbox Code Playgroud)
更新
不再在每次迭代时重新创建jQuery对象.
jQuery提供了.map()方法,
var selected = $(".client_associates_users input:checked").map(function(index) {
return this.value;
}).get();
Run Code Online (Sandbox Code Playgroud)
此方法将return使用回调中的任何数据创建新数组.请注意,您需要.get()在最后调用以获得真正的数组.
参考: .map()