How to get name of datatable column?

后端 未结 5 1434
春和景丽
春和景丽 2021-02-18 16:25

I\'m using DataTable 1.10.9 (from https://datatables.net). Columns for the datatable are defined at the initialization step in javascript and each column has a unique name, e.g.

相关标签:
5条回答
  • 2021-02-18 16:36

    below code worked for me

    this.api().columns().every(function() {
      console.log( this.header().textContent )
    })
    

    also you can add a specific html class for only specific column names like having that class

    this.api().columns(".myColumnClass").every(function() {
      console.log( this.header().textContent )
    })
    
    0 讨论(0)
  • 2021-02-18 16:37

    Documentation shows that columns().every() sets this to the current column's column() object. Further examination of the column object shows that it has a column().data() method which returns the data the column contains as an array of values. This should provide the data you need.

    0 讨论(0)
  • 2021-02-18 16:46

    You can retrieve the initialization options through table.settings().init() - and by that the columns definition this way :

    var columns = table.settings().init().columns;
    

    When clicking on a cell / <td> you can find the column index by (best practice in case of hidden columns) :

    var colIndex = table.cell(this).index().column;
    

    An example of a click handler that alerts the corresponding column.name when a cell is clicked

    $("#example").on('click', 'td', function() {
        //get the initialization options
        var columns = table.settings().init().columns;
        //get the index of the clicked cell
        var colIndex = table.cell(this).index().column;
        alert('you clicked on the column with the name '+columns[colIndex].name);
    })
    

    Your every() example would be

    var columns = table.settings().init().columns;
    table.columns().every(function(index) { 
        console.log(columns[index].name);
    })  
    

    demo -> http://jsfiddle.net/6fstLmb6/

    0 讨论(0)
  • 2021-02-18 16:48

    The following should work for you as per the API document:

    var tableColumns = [{
        name: 'first-name'
    }, {
        name: 'last-name'
    }, {
        name: 'position'
    }, {
        name: 'location'
    }, {
        name: 'salary'
    }]
    
    var table = $('#example').DataTable({
        tableColumns
    });
    
    table.columns().every(function (index) {
    
        console.log(tableColumns[index].name);
    
    });
    
    0 讨论(0)
  • 2021-02-18 16:58

    You can try using this another method. "index" variable is a column of your thead. This method will get the thead column of your table and read the text inside tag.

    dataTable.column(index).header().textContent

    0 讨论(0)
提交回复
热议问题