首页 > 解决方案 > How to iterate through all column headers in jQuery Datatables

问题描述

I am using a "fnDrawCallback" in Datatables to get the all column headers names () for that I am using the code below

"fnDrawCallback": function () {
    table.column().every( function () {
        var data = this.data();
        var title = table.columns().header();

        console.log($(title).html());
    } );

I can get the column header name for first column . I want to know how can I iterate through all columns in table and get all the header () name?

标签: jquerydatatablesiteratordatatables-1.10jquery-datatables-editor

解决方案


The simplest way I know to do this is with some jQuery inside the drawCallback option:

<script type="text/javascript">

  $(document).ready(function() {

    $('#example').DataTable( {

      "drawCallback": function ( settings ) {
        $('#example thead tr th').each(function() {
          console.log( $(this).html() );
        }); 
      }

    } );

  } );

</script>

I am using the more recent drawCallback, not the older legacy fnDrawCallback (but both do work).


Just to note: In your question, you are using table.column().every( function () {...}. I can't see how you are defining your table variable, in your example. So if my suggested approach is not suitable, perhaps you can edit your question to show the context in which you are using fnDrawCallback.


Update

If you want to hide one or more columns based on the names of the column headings, then you can take the above code and modify it as follows:

<script type="text/javascript">

  $(document).ready(function() {

    $('#example').DataTable( {

      "drawCallback": function ( settings ) {
        var tbl = $('#example').DataTable();

        var colIndex = 0;
        $('#example thead tr th').each(function() {
          var colHeading = $(this).html();
          if (colHeading === 'Office' || colHeading === 'Age') {
            tbl.columns( colIndex ).visible( false );
          }
          colIndex += 1;
        }); 
      }

    } );

  } );

</script>

In the above example, I have a table where the "Office" and "Age" columns are hidden when the table is drawn.


推荐阅读