简体   繁体   English

在jQuery Datatable中选择一行时如何检测空表

[英]How to detect empty table when selecting a row in a jQuery Datatable

Giving a simple table like this 给这样一个简单的表

<table id="exampleTable" class="table hover nowrap">
   <thead>
      <tr>
         <th>Id</th>
         <th>Name</th>
      </tr>
   </thead></table>

Also, using the jQuery Datatable plugin and making the rows selectable, like in this example . 同样,使用jQuery Datatable插件并使行可以选择,如本示例所示 The Javascript goes like this: 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');
        }
    } );

So, when the table is empty, it shows a selectable row which says something like: 因此,当表为空时,它将显示一个可选择的行,其内容类似于:

No data available in table 表中无可用数据

How to detect the table is empty and not allow selection on that kind of "message rows"? 如何检测表是否为空,并且不允许在这种“消息行”上进行选择?

Here is a fiddle with the code. 这是代码的摆弄

you can check if there is td with the class dataTables_empty like this: 您可以像这样检查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');
        }
    } );

You can use the - .row().data() method to see if there is data. 您可以使用.row().data()方法查看是否有数据。 if this returns undefined, you can disable selection of the row. 如果返回未定义,则可以禁用该行的选择。

i also think this would be an ideal solution instead of dom traversal which is more expensive. 我还认为这将是一个理想的解决方案,而不是更昂贵的dom遍历。 what do you guys think ? 你们有什么感想 ?

below is the updated fiddle. 以下是更新的小提琴。 you can comment the tbody from the html to test it. 您可以通过html注释tbody以对其进行测试。

Let me know if this helps. 让我知道是否有帮助。

Modified Fiddle 改良的小提琴

inside your click method, add before everything 在点击方法中,在所有内容之前添加

if($('#exampleTable tbody tr td').length == 1){
      return;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM