Loop through DataTables table to get all cells content

后端 未结 4 1532
北恋
北恋 2021-02-04 01:21

I am using jquery dataTables to generate the paginated table on my site. I need to run a process that grabs all of the data out of a particular column. Something like :

<
相关标签:
4条回答
  • 2021-02-04 01:47

    jQuery.map combined with fnGetData() makes for a compact solution. The following function will return a one-dimensional array containing all the values from obj_dtable's nth column:

    function getDataTableColumn(obj_dtable,n) {
        return $.map(obj_dtable.fnGetData(), function(val) {
            return val[n];
        });
    };
    
    0 讨论(0)
  • 2021-02-04 02:07

    You'll want to use the "EQ" selector. It starts at the index of "0", so if you have..

    <tr>
      <td>0</td>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    

    Then by using

     $("td").eq(3); // last one
     $("td").eq(2); //returns "2"
    

    Make sense?

    http://api.jquery.com/eq-selector/

    0 讨论(0)
  • 2021-02-04 02:08

    Here's a method using fnGetData()

    First get the data from plugin which will be all rows visible or not. Loop over each row data array, and push index=1( second cell) into new array

         oTable = $('#example').dataTable();
    
          var secondCellArray=[];
          $.each( oTable.fnGetData(), function(i, row){
              secondCellArray.push( row[1]);
        })
    
         console.log( secondCellArray)
    

    EDit : working demo...look in console after render

    http://live.datatables.net/apixiv/edit#javascript,html

    0 讨论(0)
  • 2021-02-04 02:14

    To access all the rows, you can do:

    var rows = $("#myTable").dataTable().fnGetNodes();
    

    In your case, this should work:

       $('.testLink').click(function(){
            var cells = [];
            var rows = $("#myTable").dataTable().fnGetNodes();
            for(var i=0;i<rows.length;i++)
            {
                // Get HTML of 3rd column (for example)
                cells.push($(rows[i]).find("td:eq(2)").html()); 
            }
            console.log(cells);
        });
    
    0 讨论(0)
提交回复
热议问题