我想在特定行的td中添加一个类。我不想对数字索引大惊小怪,而是通过其列的名称访问td。换句话说,我想做这样的事情:
for each row in the table where the column "role" contains "some text"
do add the "red" class to the td in the "email" column.
我找到了办法,但我对此并不满意;我发现它太复杂了。有人有更简单的建议吗?
在下面的示例中,我添加了类" red"列中的td"电子邮件"对于每一行都有一些文字"在"角色"柱:
tab = $("#myTable").dataTable({
"data": dataset,
"columns": [
{ "data": "uid", name: "uid" },
{ "data": "name", name: "name"},
{ "data": "role", name: "role"},
{ "data": "email", name: "email"}
]
});
function GetTdByName(row, column_name) {
var idx = row.nodes().column(column_name + ":name")[0];
var selector = "td:eq(" + idx + ")";
return row.nodes().to$().find(selector)
}
$("#btn").click(function() {
var ta = $('#myTable').DataTable();
ta.rows().every(function () {
if ($.inArray(this.data().role , ["some text", "some other text,"] ) > -1) {
GetTdByName(this, "email").addClass("red");
}
})
})
我找到了一种更简洁的方法。实际上,大多数此解决方案都可以在官方文档中找到:column-selector
ta.rows().every(function () {
if ($.inArray(this.data().role , ["some text", "some other text,"] ) > -1) {
$(ta.column("email:name").nodes()[this.index()]).addClass("red");
}
})
答案 0 :(得分:1)
有一个内置的回调:fnRowCallback。它可能不是您想要的代码,您使用按钮单击来应用该类,但这是您使用fnRowCallback
将该类应用于表格渲染的方式:
tab = $("#myTable").dataTable({
"data": dataset,
"columns": [
{ "data": "uid", name: "uid" },
{ "data": "name", name: "name"},
{ "data": "role", name: "role"},
{ "data": "email", name: "email"}
],
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
if(aData[2] == 'some text'){
$('td:eq(3)', nRow).addClass('red');
}
},
...