使用 Laravel DataTables 为单个单元格设置背景颜色属性

Set background color attribute for single cell with Laravel DataTables

我正在使用 Yajra Laravel 数据表来显示服务器端 ajax 负载的数据,以防止长时间加载大量数据。

现在我想根据状态(和其他选项)连续为单个 TD 着色

我发现我可以轻松地将参数添加到整行,具体取决于选项:

->setRowAttr([
    'style' => function($item){
        return $item->disabled ? 'background-color: #ff0000;' : 'background-color: #00ff00;';
    }
])

这就产生了我:

但我不需要为整行着色,只需为 Bookings TD(在本例中)着色,因为将对活动状态应用不同的颜色 + 对房间组应用另一种颜色,如下所示:

如何实现?

PS:我正在使用 Laravel 5.3 和 Datatavles 6

好的,阅读此文档后自己解决了这个问题
http://datatables.net/release-datatables/examples/advanced_init/row_callback.html:

首先,我在 Datatables make() 调用之前添加了额外的列,因为原始内容会被语言输出覆盖,如下所示:

->addColumn('active', function ($item) {
    return $item->disabled ? 0 : 1;
})
->editColumn('disabled', function ($item) {
    $item->disabled ? t('No') : t('Yes');
})

然后我在数据调用后立即对 JS 部分添加了检查:

serverSide: true,
ajax: {
    url: ...,
    type: "get"
},
columns: [
    ...
    {data: 'disabled', name: 'disabled'},
    ...
],
createdRow: function ( row, data, index ) {
    ...
    if ( data['active'] == 1 ) {
        $('td', row).eq(5).addClass('success');
    } else {
        $('td', row).eq(5).addClass('danger');
    }
    ...
},

请参考

php:

DataTables::of($query)
->addColumn('stylesheet', function ($record) {
                                return [
                                    [
                                        'col' => 11,
                                        'style' => [
                                            'background' => '#080',
                                        ],
                                    ],
                                    [
                                        'col' => 12,
                                        'style' => [
                                            'background' => '#c00',
                                            'color' => '#fff',
                                        ],
                                    ],
                                ];
                            });

javascript:

DataTable({
columns: [...],
createdRow: function (row, data, dataIndex, cells) {
                if (data.stylesheet) {
                    $.each(data.stylesheet, function (k, rowStyle) {
                        $(cells[rowStyle.col]).css(rowStyle.style);
                    });
                }
            },
})

结果: