Javascript 如何遍历 DataTables jQuery 中的所有行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29077902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through all rows in DataTables jQuery?
提问by Vivien Pipo
I am using jquery plugin DataTables for building nice table
我使用jQuery插件dataTables建立好的表
var table = $('#example').DataTable({
"data": source
});
I would like that make an each for all rows in table
我想为表中的所有行创建一个
Unfortunately this way may be out of date and does't work with new version (it launchs an error)
不幸的是,这种方式可能已经过时并且不适用于新版本(它会引发错误)
$(table.fnGetNodes()).each(function () {
});
And this way only works only for visibles rows (10 first rows because other rows are paginated)
这种方式仅适用于可见行(前 10 行,因为其他行是分页的)
table.each( function ( value, index ) {
console.log( 'Data in index: '+index+' is: '+value );
} );
Do you known how to loop to all rows please?
你知道如何循环到所有行吗?
回答by Vivien Pipo
I finally found:
我终于发现:
var data = table.rows().data();
data.each(function (value, index) {
console.log(`For index ${index}, data value is ${value}`);
});
回答by Athman
Datatables have an iterator for each row rows().every()with thisreferring to the context of the current row being iterated.
数据表具有用于每行的迭代器的行()。每一()与this参照当前行之中的上下文中重复。
tableName.rows().every(function(){
console.log(this.data());
});
回答by Mohd Abdul Mujib
If you are using the legacy DataTables then you can get all the rows even the paginated ones, as shown below...
如果您使用的是旧版 DataTables,那么您可以获得所有行,甚至是分页的行,如下所示...
table.fnGetNodes(); // table is the datatables object.
So we can loop through the rows by using .each()method provided by jQuery.
所以我们可以使用.each()提供的方法遍历行jQuery。
jQuery(table.fnGetNodes()).each(function () {
// You can use `jQuery(this).` to access each row, and process it further.
});
回答by Asad Naeem
for example, this data has three fields UserID, UserName and isActive and we want to show only active users The following code will return all the rows.
例如,此数据包含三个字段 UserID、UserName 和 isActive,我们只想显示活动用户 以下代码将返回所有行。
var data = $('#myDataTable').DataTable().rows.data();
We will print only active users
我们将只打印活跃用户
data.each(function (value, index) {
if (value.isActive)
{
console.log(value.UserID);
console.log(value.UserName);
}
});

