jquery datatables - 按列名称获取 td

标签 jquery datatables

我想将一个类添加到特定行中的 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/

相关文章:

javascript - 查找多个 JavaScript 数组之间的匹配项

JQUERY 数据表 -- 类型错误 : k is undefined - Dynamically forming Table with MVC

twitter-bootstrap - Angular4 CLI 项目中的 Bootstrap 4 Datatablejs

datatables - 对数据表中的筛选列求和

javascript - DataTables 表不显示

javascript - 数据表: brake with url

javascript - 数据表 - 渲染列上的 api.column().data() 调用

JQuery 循环函数仅适用于最后一个元素

javascript - BlockUI 强制所有元素居中

javascript - 向所选段落添加类(contenteditable div)