【发布时间】:2018-11-20 18:04:24
【问题描述】:
当我使用复选框选择一行时,我想访问我的 jQuery 数据表中的行数据。我已经知道如何访问行数据,但它作为字符串返回,我需要使用 javascript 字符串函数来拆分数据并获取我想要的值;我不知道当我的表中有超过 10k 行数据时这是否可行。
有没有办法使用复选框作为行选择器访问行的特定值,现在我想要的是获取所选行的rowId,这个Id存储在表格的复选框列中。
这是我的表格的 HTML
<table id="MyTable" class="display table" cellspacing="0" width="100%">
<thead>
<tr>
<th>
<input type="checkbox" class="form-check-input" id="exampleCheck1">
</th>
<th>
Name
</th>
<th>
Last Name
</div>
</th>
<th>
Age
<br>
</th>
</tr>
</thead>
<tbody id="tablePersons">
<tr id="PersonId" style="display:none" class="result-item">
<td></td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</tbody>
</table>
我的数据表定义
var personTable= $('#MyTable').DataTable({
bInfo: false, paging: false, bInfo : false,
dom: 'lrtp',
columnDefs: [ {
targets: 0,
checkboxes: {
selectRow: true
}
},
{
targets: 1,
className: 'textcolumn-left'
},
{
targets: 2,
className: 'textcolumn-left'
},
{
targets: 3,
className: 'textcolumn-left'
}
]
});
这是我添加行的方法
personTable.row.add(['<input class="personTableCheckboxes" type="checkbox" value="'+item.personID+'" id="'+item.personID+'"> ',
item.name, item.lastName, item.age]);
这是我获取行数据的方式
var listOfCheckedRows = personTable.column(0).checkboxes.selected();
如果我执行console.log(listOfCheckedRows),我会得到一个可以迭代的数组,如果我像这样迭代它
$.each(listOfCheckedRows , function(index, rowId){
console.log(rowId) ;
});
$.each 循环内的console.log 包含一个字符串,该字符串包含数据行的html,我可以执行javascript 字符串函数来拆分字符串并获取代表id 的复选框的id行,但我不想这样做,因为如果表有超过 10k 行,这将无法有效。
我想迭代该数组并获取所有行 id 并将其存储在另一个数组中,有没有办法可以获取所选复选框的 id 值?无需对每个循环或字符串拆分函数执行此操作即可获取表示行 id 的复选框元素的 id。
【问题讨论】:
标签: javascript jquery html-table datatables