[英]How to detect empty table when selecting a row in a jQuery Datatable
给这样一个简单的表
<table id="exampleTable" class="table hover nowrap">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead></table>
同样,使用jQuery Datatable插件并使行可以选择,如本示例所示 。 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');
}
} );
因此,当表为空时,它将显示一个可选择的行,其内容类似于:
表中无可用数据
如何检测表是否为空,并且不允许在这种“消息行”上进行选择?
您可以像这样检查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');
}
} );
您可以使用.row().data()
方法查看是否有数据。 如果返回未定义,则可以禁用该行的选择。
我还认为这将是一个理想的解决方案,而不是更昂贵的dom遍历。 你们有什么感想 ?
以下是更新的小提琴。 您可以通过html注释tbody以对其进行测试。
让我知道是否有帮助。
在点击方法中,在所有内容之前添加
if($('#exampleTable tbody tr td').length == 1){
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.