如何在DataTablesjQuery中循环遍历所有行

How to loop through all rows in DataTables jQuery?

本文关键字:遍历 循环 DataTablesjQuery      更新时间:2023-09-26

我正在使用jquery插件DataTables来构建漂亮的表

  var table = $('#example').DataTable({
    "data": source
});

我想为表中的所有行制作一个

不幸的是,这种方式可能已经过时,不适用于新版本(它启动了一个错误)

$(table.fnGetNodes()).each(function () {
});

这种方式只适用于可见行(第一行10行,因为其他行已分页)

 table.each( function ( value, index ) {
    console.log( 'Data in index: '+index+' is: '+value );
} );

你知道如何循环到所有的行吗?

我终于找到了:

 var data = table.rows().data();
 data.each(function (value, index) {
     console.log(`For index ${index}, data value is ${value}`);
 });

数据表为每行rows().every()都有一个迭代器,this指的是正在迭代的当前行的上下文。

tableName.rows().every(function(){
    console.log(this.data());
});

如果您使用的是遗留的DataTables,那么您可以获得所有的行,甚至是分页的行,如下所示。。。

table.fnGetNodes(); // table is the datatables object.

因此,我们可以使用jQuery提供的.each()方法来遍历行。

jQuery(table.fnGetNodes()).each(function () {
// You can use `jQuery(this).` to access each row, and process it further.            
});

例如,该数据有三个字段UserID、UserName和isActive,我们希望只显示活动用户以下代码将返回所有行。

var data = $('#myDataTable').DataTable().rows().data();

我们将只打印活动用户

data.each(function (value, index) {
  if (value.isActive)
  {
     console.log(value.UserID);
     console.log(value.UserName);
  }
});