基于单元格值的jQuery Datatable行颜色更改

时间:2018-08-09 11:23:10

标签: jquery datatables

我想根据单元格值更改行背景颜色和文本颜色。我的
我的HTML代码(波纹管)

<button id="refersh">Refresh</button>
<button id="AddRow">Add New Row</button>
<table id="stdTable" class="table table-bordered table-striped" width="100%">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Age</th>
            <th>Date of birth</th>
            <th>Edit/View</th>
        </tr>
    </thead>
</table>

数据表版本为v 1.10.12。 数据加载方法是ajax。

2 个答案:

答案 0 :(得分:0)

将脚本更改为波纹管。请检查“ fnRowCallback”部分

 var dataset = [
        [
            Id = "001",
            Name = "nn",
            Age = "Age",
            DateofBirth = "125"
        ],
         [
            Id = "001",
            Name = "nn",
            Age = "Age",
            DateofBirth = "125"
         ]
    ];    

$('#stdTable').DataTable({
        processing: true,
        serverSide: false,
        ordering: true,
        paging: true,
        searching: true,
        columns: [
           { title: "Id" },
           { title: "Name" },
           { title: "Age" },
           { title: "DateofBirth" },
           { title: "View Data" }
        ],
        columns: [
          { data: "Id" },
          { data: "Name" },
          { data: "Age" },
          { data: "DateofBirth" },
          {
              data: null,
              defaultContent: "<button class='tblview'>View Id</button><button class='tblDelete'>Delete</button>"
          }
        ],
        data:dataset,
        "columnDefs": [
            {
                "targets": 0,
                "visible": false
            }
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
            if (aData.Age == "20") {
                //cell background color
                $(nRow).find('td:eq(1)').css('background-color', '#ffc2c2');
            }
            else if (aData.Age == "10") {
                //row background color
                $('td', nRow).css('background-color', 'Orange');
            }
            else if (aData.Age == "25") {
                //cell text color
                 $('td', nRow).css('color', 'red');
            }
        }
    });
});

答案 1 :(得分:0)

使用以下createdRow函数:

"createdRow": function( row, data, dataIndex ) {
                if ( data["LAYOUT"] == "N" ) {
                    $( row ).css( "background-color", "Orange" );
                    $( row ).addClass( "highlight" );
                }
            }