我只希望numberOfSelectedRows仅显示我选择的行。 例如,如果我选择2行,我只希望此变量为2。但是对我来说,它出现在所有行中。 与使用api.rows()。every()函数时相同。在docs for rows().every()中,它表示仅循环选定的行,但对我来说,它循环遍历表中的所有行。我在做什么错了?
index.js
$(document).ready(function () {
$('#example').DataTable({
dom: 'Bfrtip',
select: true,
buttons: [{
extend: 'copyHtml5',
text: 'Copy Selected Rows',
header: false,
customize: function(data, config, api){
var numberOfSelectedRows = api.rows().data().length;
console.log(numberOfSelectedRows);
}
}]
});
});
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.2/css/buttons.dataTables.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.print.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.2.7/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="index.js"></script>
<body>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
</tbody>
</table>
</body>
</html>
答案 0 :(得分:0)
这需要从以下更改:
var numberOfSelectedRows = api.rows().data().length
对此:
var numberOfSelectedRows = api.rows('.selected').data().length
答案 1 :(得分:0)
您可以使用计数功能来获取选定的行数。
计算所选类别的行数:
var table = $('#example').DataTable();
alert( 'Rows '+table.rows( '.selected' ).count()+' are selected' );
计算表中数据条目(即行)的数量:
var table = $('#example').DataTable();
if ( ! table.data().count() ) {
alert( 'Empty table' );
}
您可以看到文档here