检查数据表是否为空

mer*_*esi 4 datatable jquery

我尝试同时构建一个既是JQuery treeTable又是JQuery数据表的表.请注意,我的问题不是关于如何使用它,我可以查看没有问题,如果我填写"表".

但是当我向我的treetable建筑代码发送一个空数组时,我收到错误.

这是问题行:

$('#table tbody tr').each(function(){
                        console.log(this);
                        if(mytable.fnGetData(mytable.fnGetPosition(this))[4]){
                            console.log('in set child before');
                            $(this).addClass('child-of-'+mytable.fnGetData(mytable.fnGetPosition(this))[4]);
                            console.log('in set child after');
                        }
                        $(this).attr('id', mytable.fnGetData(mytable.fnGetPosition(this))[0]);
                    });
Run Code Online (Sandbox Code Playgroud)

当我没有填充表格,尽管我的愿望,过程进入上述循环,并且

console.log(this) 打印出来:

<tr class="odd"><td valign="top" colspan="4" class="dataTables_empty">No data available in table</td></tr>
Run Code Online (Sandbox Code Playgroud)

因此它会生成错误,因为行数据不是预期的.

我想问一下,如果它是一个填充的"数据"或一个空的警告行,最优雅的控制方法是什么?检查"dataTables_empty"的"类"是否合适?

或者,如果表为空,还有其他方法可以不通过上面的循环.

Dav*_*ano 7

如何知道数据表是否为空

var table = $('#idTable').DataTable();

if ( ! table.data().any() ) {
    alert( 'Empty table' );
}
Run Code Online (Sandbox Code Playgroud)


Dev*_*Dev 6

您还可以使用page.info()检查dataTable是否为空,如此stackoverflow帖子中所述.例如.

    //gives the total number of filtered records
    var totalDisplayRecord = $(".dTable").DataTable().page.info().recordsDisplay
(totalDisplayRecord === 0)? alert("table is empty") : alert("table is not empty");
Run Code Online (Sandbox Code Playgroud)

要么

//gives the total number of records in table
var totalRecords =$(".dTable").DataTable().page.info().recordsTotal;
//test if dataTable is empty
(totalRecords === 0)? alert("table is empty") : alert("table is not empty");
Run Code Online (Sandbox Code Playgroud)


ela*_*ver 1

论坛中,这可能是您正在寻找的内容:

table.fnSettings().aoData.length
Run Code Online (Sandbox Code Playgroud)

为您提供表中数据的长度。因此,如果它等于 0,则没有数据。

    if(table.fnSettings().aoData.length===0) {
        alert('no data');
    } else {
        alert('data exists!');
    }
Run Code Online (Sandbox Code Playgroud)