数据表.如何遍历所有行并获取每个tr条目的ID [英] Datatables. How to loop through all rows and get id of each tr entry
问题描述
此问题的目标是JQuery
的Datatables
插件.
This questions targets to Datatables
plug-in for JQuery
.
我需要遍历所有表行(甚至分页),并获取每个tr
元素的id
.
I need to loop through all table rows (even paginated) and get id
of each tr
element.
这样的HTML表:
<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>
因此,如果最后2个字符不等于en
,则需要遍历每一行并隐藏行(通过此检查,一切正常,我使用的是substr
).
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);
});
但是我找不到从tr
中获取id
的方法(使用此示例数据etc_1_en
,etc_1_ru
等).有人可以帮我吗?
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?
我尝试将函数id
作为参数传递,但它返回-undefined
.
I've tried to pass in function id
as parameter, but it returns - undefined
.
推荐答案
您可以使用rows().every()
遍历rows()
.这样,您将可以访问row
对象,这将同时为您提供data
和id
.
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);
});
更多信息: https://datatables.net/reference/api/rows ().every()
这篇关于数据表.如何遍历所有行并获取每个tr条目的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!