jQuery DataTable 设置多选框选中
在开发网页时,经常会遇到需要展示数据表格并对数据进行选择操作的情况。而jQuery DataTable 是一个非常方便且功能强大的表格插件,可以帮助我们快速地展示数据并进行各种操作。在某些情况下,我们可能需要在表格中添加多选框,并且需要根据需求设置多选框的选中状态。接下来,我们将详细介绍如何在jQuery DataTable 中设置多选框选中的方法。
准备工作
在开始之前,我们需要先引入 jQuery 和 jQuery DataTable 的相关文件。可以通过 CDN 来引入这些文件,也可以下载到本地并引入。下面是一个简单的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery DataTable 多选框选中</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
</head>
<body>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="select-checkbox"></td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
</tr>
<tr>
<td><input type="checkbox" class="select-checkbox"></td>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
</tr>
<tr>
<td><input type="checkbox" class="select-checkbox"></td>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script>
(document).ready(function() {
var table =('#example').DataTable({
select: {
style: 'multi'
}
});
});
</script>
</body>
</html>
在上面的示例中,我们引入了 jQuery 和 jQuery DataTable 的文件,并创建了一个简单的表格。表格中的每一行都包含一个多选框用来选择数据,然后在 JavaScript 中初始化了 DataTable,并设置了 select: { style: 'multi' }
选项,表示支持多选。接下来我们将介绍如何设置多选框的选中状态。
设置多选框选中
设置全部多选框选中
如果我们想要一次性将所有的多选框设置为选中状态,可以使用 DataTable 的 rows().select()
方法。该方法会将所有当前可见的行选中。
$('#example').DataTable().rows().select();
设置部分多选框选中
如果我们只想要设置某几行的多选框为选中状态,可以使用 DataTable 的 row().select()
方法。该方法接收一个参数,表示要选中的行索引,从 0 开始计数。
$('#example').DataTable().row(1).select();
获取选中的多选框
若想要获取当前选中的多选框的行数据,可以使用 DataTable 的 rows( { selected: true } )
方法,该方法会返回一个包含选中行数据的对象数组。
var selectedRows = $('#example').DataTable().rows( { selected: true } ).data();
selectedRows.each(function() {
console.log(this);
});
结语
通过上述方法,我们可以在 jQuery DataTable 中方便地设置多选框的选中状态。这在需要进行批量操作或者筛选数据时非常有用。