jQuery 如何根据jQuery数据表中的列值设置表行的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16353455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:59:53  来源:igfitidea点击:

How to set color for table rows based on column value in jQuery data table

jquerydatatables

提问by PSR

I am using jQuery datatables.I have the data like as follows

我正在使用 jQuery 数据表。我有如下数据

Column1 Column2 Column3
-----------------------
 AAA    BBB     CCC
 AAA    GGG     YYY
 BBB    ooo     LLL

Now in column1 for first 2 rows i have same value AAA.I want to apply some color to those rows.And then another color for third row.Like this i have 30 records.Is it possible to do this.If possible how i can do this.I am using jQuery data tables.Thanks in advance..

现在在第 1 列的前 2 行中,我有相同的值AAA。我想对这些行应用一些颜色。然后第三行的另一种颜色。像这样我有 30 条记录。是否可以这样做。如果可能,我该怎么做这个。我正在使用 jQuery 数据表。提前致谢..

回答by Arun P Johny

Use the fnRowCallback(or newer rowCallback) to achieve this

使用fnRowCallback(或更新的rowCallback)来实现这一点

$('#example').dataTable({
    "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
        switch(aData[0]){
            case 'AAAA':
                $(nRow).css('color', 'red')
                break;
            case 'BBBB':
                $(nRow).css('color', 'green')
                break;
            case 'CCCC':
                $(nRow).css('color', 'blue')
                break;
        }
    }
});

Demo: Fiddle

演示:小提琴

回答by Herve MARTIN

API has recently changed, you should now use aData['Column1'] instead of aData[0]

API 最近发生了变化,您现在应该使用 aData['Column1'] 而不是 aData[0]

回答by gArn

createdRow functionality was added in v 1.10

createdRow 功能是在 v 1.10 中添加的

This callback is executed when a TR element is created (and all TD child elements have been inserted), or registered if using a DOM source, allowing manipulation of the TR element.

This is particularly useful when using deferred rendering (deferRender) or server-side processing (serverSide) so you can add events, class name information or otherwise format the row when it is created.

此回调在创建 TR 元素时执行(并且所有 TD 子元素都已插入),或者在使用 DOM 源时注册,从而允许对 TR 元素进行操作。

这在使用延迟渲染 (deferRender) 或服务器端处理 (serverSide) 时特别有用,因此您可以在创建行时添加事件、类名信息或以其他方式格式化行。

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

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

Example:

例子:

    $('#example').dataTable({
        // ...
        "createdRow": function( row, data, dataIndex ) {
            if ( data["column_index"] == "column_value" ) {
                $( row ).css( "background-color", "Orange" );
                $( row ).addClass( "warning" );
            }
        },
        // ...
    });