if *_*one 122 javascript jquery
我试图获取当前检查的所有复选框的值并将它们存储到数组中.到目前为止,这是我的代码:
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("#find-table input:checkbox:checked").map(function(){
return $(this).val();
});
console.log(searchIDs);
});
Run Code Online (Sandbox Code Playgroud)
然而,这比我需要的更多.我不仅得到了价值,还有其他一些我不想要的东西.
["51729b62c9f2673e4c000004","517299e7c9f26782a7000003","51729975c9f267f3b5000002",prevObject:jQuery.fn.jQuery.init [3],context:document,jquery:"1.9.1",constructor:function,init:function ...]
我想要ID(在这种情况下前3项).
通过使用$.each值并将值推送到数组,我获得了所需的输出:
$("#find-table input:checkbox:checked").each(function(){ myArray.push($(this).val()); })
Run Code Online (Sandbox Code Playgroud)
["51729b62c9f2673e4c000004","517299e7c9f26782a7000003","51729975c9f267f3b5000002"]
但是我想使用$.map它,因为它为我节省了一行代码并且更漂亮.
谢谢
And*_*ker 248
.get()在最后调用将生成的jQuery对象转换为真正的数组.
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("#find-table input:checkbox:checked").map(function(){
return $(this).val();
}).get(); // <----
console.log(searchIDs);
});
Run Code Online (Sandbox Code Playgroud)
根据文件:
由于返回值是一个包含数组的jQuery对象,因此在结果上调用.get()以使用基本数组是很常见的.
Cri*_*ufu 21
$(document).ready(function(){
var searchIDs = $('input:checked').map(function(){
return $(this).val();
});
console.log(searchIDs.get());
});
Run Code Online (Sandbox Code Playgroud)
只需调用get(),您就可以获得规范中编写的数组:http://api.jquery.com/map/
$(':checkbox').map(function() {
return this.id;
}).get().join();
Run Code Online (Sandbox Code Playgroud)
tym*_*eJV 18
您需要添加.toArray()到.map()函数的末尾
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("#find-table input:checkbox:checked").map(function(){
return $(this).val();
}).toArray();
console.log(searchIDs);
});
Run Code Online (Sandbox Code Playgroud)
Mar*_*yer 10
我稍微重构了你的代码并相信我带来了你正在寻找的解决方案.基本上不是设置searchIDs为.map()我刚刚将值推入数组的结果.
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = [];
$("#find-table input:checkbox:checked").map(function(){
searchIDs.push($(this).val());
});
console.log(searchIDs);
});
Run Code Online (Sandbox Code Playgroud)
我创建了一个运行代码的小提琴.
var ids = [];
$('input[id="find-table"]:checked').each(function() {
ids.push(this.value);
});
Run Code Online (Sandbox Code Playgroud)
这个对我有用!