最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - datatables number of columns - Stack Overflow

programmeradmin1浏览0评论

How do i get the number of columns in a datatable?

I can get the number of rows by doing oTable.fnGetData().length but how do I get the number of columns so I can Iterate over each cell like this:

var numColumns = //How to get the number of columns?
    for(var r=0;r<oTable.fnGetData().length;r++){
        for(var c=0;c <= numColumns;c++){
            console.log("[R]: "+r+ "[C]: "+c+ " data: "+oTable.fnGetData(r,c));   
        }
    }

How do i get the number of columns in a datatable?

I can get the number of rows by doing oTable.fnGetData().length but how do I get the number of columns so I can Iterate over each cell like this:

var numColumns = //How to get the number of columns?
    for(var r=0;r<oTable.fnGetData().length;r++){
        for(var c=0;c <= numColumns;c++){
            console.log("[R]: "+r+ "[C]: "+c+ " data: "+oTable.fnGetData(r,c));   
        }
    }
Share Improve this question asked May 30, 2012 at 0:47 AstronautAstronaut 7,04118 gold badges64 silver badges100 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 21

GET NUMBER OF COLUMNS

  • DataTables 1.9+

    // Get number of all columns
    var numCols = $('#example').dataTable().fnSettings().aoColumns.length;
    
    // Get number of visible columns
    var numCols = $('#example thead th').length;
    

    See this jsFiddle for demonstration.

  • DataTables 1.10+

    // Get number of all columns
    var numCols = $('#example').DataTable().columns().nodes().length;
    
    // Get number of visible columns
    var numCols = $('#example').DataTable().columns(':visible').nodes().length;
    
    // Get number of visible columns (alternative way)
    var numCols = $('#example thead th').length;
    

    See this jsFiddle for demonstration.

ITERATE OVER EACH CELL

  • DataTables 1.10.6+

    $('#example').DataTable().cells().every( function (rowIndex, colIndex) {
        var data = this.data();
    
        console.log("Row:", rowIndex, "Col:", colIndex, "Data:", data);
    });
    

The fnGetData can be used to get a single data row. So, you can simply check the length of the data row for the number of columns.

Example:

oTable.fnGetData(someRowNumber).length;

The above will return the number of columns in that data row.

发布评论

评论列表(0)

  1. 暂无评论