Datatables. How to loop through all rows and get id of each tr entry

橙三吉。 提交于 2021-02-08 04:29:29

问题


This questions targets to Datatables plug-in for JQuery.

I need to loop through all table rows (even paginated) and get id of each tr element.

HTML table like this:

<table>
  <thead>
    <tr>
      <th>Header content 1</th>
      <th>Header content 2</th>
    </tr>
  </thead>
  <tbody>
    <tr id="etc_1_en">
      <td>Etc 1</td>
      <td>Etc 2</td>
    </tr>
    <tr id="etc_1_ru">
      <td>Etc 3</td>
      <td>Etc 4</td>
    </tr>   
    <tr id="etc_1_fr">
      <td>Etc 5</td>
      <td>Etc 6</td>
    </tr>   
    <tr id="etc_2_en">
      <td>Foo 1</td>
      <td>Foo 2</td>
    </tr>
    <tr id="etc_2_ru">
      <td>Foo 3</td>
      <td>Foo 4</td>
    </tr>   
    <tr id="etc_2_fr">
      <td>Foo 5</td>
      <td>Foo 6</td>
    </tr>       
  </tbody>
</table>

So I need to loop through each row and hide row if last 2 characters is not equal to en (with this checking everything fine, I'm using substr).

I can loop through all rows in following:

tbl = $('#myTable').DataTable();
var data = tbl.rows().data();

data.each(function (value, index) {
    console.log('Data in index: ' + index + ' is: ' + value);
});

But I can't find a way to get id of tr (with this sample data etc_1_en, etc_1_ru and so on). Could someone help me?

I've tried to pass in function id as parameter, but it returns - undefined.


回答1:


You can loop through the rows() using rows().every(). This way you will have access to the row object, which will give you both data and id.

tbl = $('#myTable').DataTable();

tbl.rows().every(function () {
  var data = this.data();
  var id = this.id();
  console.log('Data in id: ' + id + ' index: ' + index + ' is: ' + data);
});

More info: https://datatables.net/reference/api/rows().every()



来源:https://stackoverflow.com/questions/49147871/datatables-how-to-loop-through-all-rows-and-get-id-of-each-tr-entry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!