jQuery数据表将类添加到tr

7 R*_*eds 27 javascript jquery datatables

我正在使用jQuery和datatables.我想在特定行的TR元素中添加一个类.我知道如何找到这一行.所述console.dir(row);显示row对象和与一个启动tr元件.我不能让jQuery选择器做任何事情.我错过了什么?

table = $('#resultTable').DataTable({
    aaSorting: [],
    ajax: {...},
    columnDefs: [...],
    createdRow: function (row, data, index) {
        //
        // if the second column cell is blank apply special formatting
        //
        if (data[1] == "") {
            console.dir(row);
            $('tr', row).addClass('label-warning');
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

Oza*_*zan 50

$('tr', row)正在寻找行的背景下tr元素,这意味着它会为tr元素搜索里面row设置作为上下文参数.

根据API,这应该工作

$(row).addClass("label-warning");
Run Code Online (Sandbox Code Playgroud)


Ham*_*awy 12

你只需要使用createdRow

`

$('#data-table').DataTable( {
    createdRow: function( row, data, dataIndex ) {
        // Set the data-status attribute, and add a class
        $( row ).find('td:eq(0)')
            .attr('data-status', data.status ? 'locked' : 'unlocked')
            .addClass('asset-context box');
    }
} );
Run Code Online (Sandbox Code Playgroud)

`


Ade*_*rad 12

要设置行上的 Id 属性,<tr>请使用:

//.... 
rowId: "ShipmentId",
columns: [...],
//....
Run Code Online (Sandbox Code Playgroud)

要设置类名,请<tr>使用此回调

createdRow: function (row, data, dataIndex) {
    $(row).addClass('some-class-name');
},
Run Code Online (Sandbox Code Playgroud)

参考: https: //datatables.net/reference/option/createdRow

设置使用<td>类别

"columns": [
{ 
    data:"",
    className: "my_class",
    render: function (data, type, row) { return "..."; }
},
{ 
    data:"",
    className: "my_class",
    render: function (data, type, row) { return "..."; }
},
//...
]
Run Code Online (Sandbox Code Playgroud)

'columnDefs' 类似的东西

参考: https: //datatables.net/reference/option/columns.className


Nic*_*sai 5

DataTable()。row.add()情况:

如果要在Datatables中使用行添加功能时添加类,则可以从node()方法获取TR-DOM :

var datatable = $('#resultTable').DataTable();

var trDOM = datatable.row.add( [
    "Col-1",
    "Col-2"
] ).draw().node();

$( trDOM ).addClass('myClass');
Run Code Online (Sandbox Code Playgroud)


Maj*_*ati 5

tr您还可以通过发送到数据表的 json 数据添加类。每个 json 项都有DT_RowClass.
例如:

{

    DT_RowAttr = new
    {
       attr1 = "1",
       attr2 = "2"
    }
    DT_RowClass = "majid",
    DT_RowId = "rowId"

}  
Run Code Online (Sandbox Code Playgroud)

在此示例中,DT_RowId值适用于id任何tr标签的属性,DT_RowAttr值适用于标签的某些自定义属性tr