[英]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.