[英]Return an array of all checkboxes checked upon click
我有一张表格,每一行都有一个复选框,如下所示:
<table id='users'>
<thead>
...
</thead>
<tbody>
<tr>
<td><input type='checkbox' name='users' id='someUserId'></td>
<td> some variable pid </td>
<td>...</td>
</tr>
<tr>
<td><input type='checkbox' name='users' id='someOtherId'></td>
<td> some other variable pid </td>
<td>...</td>
</tr>
...
</tbody>
</table>
现在,我想将复选框,pids旁边的列文本放入数组中,然后将数组传递给函数。 该函数应获取数组中的每个记录并对其进行处理。
到目前为止,我最好的尝试:
function myFunction(arr[]){...}
function getIds(obj){
var $table = $("#users");
alert($table.attr("id"));
var $cboxes = $table.find("input:checkbox").toArray();
alert($cboxes);
var checkedArray = [];
var pid;
for(i = 0;i < $cboxes.length; i++){
if($cboxes[i].checked){
pid = $cboxes.parent().siblings().eq(0).text();
checkedArray.push(pid);
alert(pid);
}
}
alert(checkedArray);
return checkedArray;
}
$("#button").click(function(){
var ids = getIds();
for(i = 0; i < ids.length; i++){
myFunction(ids[i]);
alert("Function executed for "+ids[i]+".");
}
});
您可以使用:checked
伪选择器和$.map
大大减少这种情况。
function process (id) { alert(id); } function find () { return $('#users').find('input:checkbox:checked').map(function () { return $(this).parent().next().text(); }).toArray(); } function handle () { find().forEach(process); } $('#btn').on('click', handle); // Pseudo-event
<table id='users'> <thead> </thead> <tbody> <tr> <td><input type='checkbox' name='users' id='someUserId'></td> <td> some variable pid </td> <td>...</td> </tr> <tr> <td><input type='checkbox' name='users' id='someOtherId'></td> <td> some other variable pid </td> <td>...</td> </tr> </tbody> </table> <button id="btn">Check!</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
如果您不想循环两次,则应将逻辑压缩到单个功能链中。 这样可以减少循环,但仍可以构建阵列以备后用。
var myNamespace = {}; function process (id) { alert('Single ID: '+ id); return id; } function find () { return $('#users').find('input:checkbox:checked').map(function () { return process($(this).parent().next().text()); }).toArray(); } function handle () { myNamespace.ids = find(); alert('All IDs: ' + myNamespace.ids) } $('#btn').on('click', handle); // Pseudo-event
<table id='users'> <thead> </thead> <tbody> <tr> <td><input type='checkbox' name='users' id='someUserId'></td> <td> some variable pid </td> <td>...</td> </tr> <tr> <td><input type='checkbox' name='users' id='someOtherId'></td> <td> some other variable pid </td> <td>...</td> </tr> </tbody> </table> <button id="btn">Check!</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
尝试这个:
function getIds() {
var chk = $("#users").find("input:checkbox");
var pId = [];
chk.each(function(){
pId.push($(this).parent().next().html());
});
return pId;
}
$(function(){
getIds().forEach(function(i){
console.log(i);
});
});
在users表中找到所有复选框,创建数组,将所有pId推入数组,然后从函数中将其返回。 然后循环遍历它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.