jQuery datatables add class to tr

2019-03-11 23:52发布

I am using jQuery and datatables. I want to add a class to the TR element of a particular row. I know how to find the row. The console.dir(row); shows the row object and that starts with a tr element. I can't get the jQuery selector to do anything though. What am I missing?

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');
        }
    }
});

4条回答
我命由我不由天
2楼-- · 2019-03-12 00:27

DataTable().row.add() situation:

If you want to add class when using row add function in Datatables, you could get the TR-DOM from node() method:

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

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

$( trDOM ).addClass('myClass');
查看更多
你好瞎i
3楼-- · 2019-03-12 00:28

Also you can add class to tr by pass through json data that you send to datatable. It's enough that every json item has DT_RowClass.
For example:

{

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

}  

In this example DT_RowId value apply to id attribute of any tr tag and DT_RowAttr value apply some custom attribute to tr tag.

查看更多
手持菜刀,她持情操
4楼-- · 2019-03-12 00:32

$('tr', row) is looking for a tr element in the context of row, meaning it will search for a tr element inside the row provided as context parameter.

According to API, this should work

$(row).addClass("label-warning");
查看更多
等我变得足够好
5楼-- · 2019-03-12 00:40

You would just have to use the 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');
    }
} );

`

查看更多
登录 后发表回答