我想将一个类添加到特定行中的 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.
我已经找到了一种方法,但我对此不太满意;我觉得太复杂了。有人有更简单的建议吗?
在下面的示例中,我为“角色”列中包含“某些文本”的每一行将“红色”类添加到“电子邮件”列中的 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");
}
})
最佳答案
有一个内置回调: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');
}
},
...
关于jquery datatables - 按列名称获取 td,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29459606/