给出一个像这样的简单表格
<table id="exampleTable" class="table hover nowrap">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead></table>
此外,使用jQuery Datatable plugin并使行可选择,如this example 。 JavaScript 是这样的:
var exampleTable = $("#exampleTable").DataTable(
{
"bDestroy": true,
"lengthChange": false,
"bPaginate": false
});
$('#exampleTable tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
$('#exampleTable tr.selected').removeClass('selected');
$(this).addClass('selected');
}
} );
因此,当表格为空时,它会显示一个可选择的行,内容如下:
No data available in table
如何检测表格为空并且不允许选择此类“消息行”?
Here is a fiddle与代码。
最佳答案
您可以检查是否存在类为 dataTables_empty 的 td,如下所示:
$('#exampleTable tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else if(! $(this).find('td.dataTables_empty').length){
$('#exampleTable').DataTable().rows().nodes().each(function(){
$(this).removeClass('selected');
});
$(this).addClass('selected');
}
} );
关于javascript - 如何在 jQuery 数据表中选择行时检测空表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41891117/