change color of datatable cell depending on values

2019-03-03 03:54发布

问题:

I am working on data table in which I have to change the color of one td depending on values coming from server.

For now, I have successfully updated the color of complete row, But I am unable to change the color of only one cell in row.

Please see the attached image for current result.

You can see it change the whole color of row BUT I only need to change the color of Second column.

here is my code :

"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
            if(aData.statusCode == "FAILED"){
                $("td", nRow).css("background-color", "Red");
            }
            if(aData.statusCode == "RUNNING"){
                 $("td", nRow).css("background-color", "green");
            }
        }

I am using version DataTables 1.10.15

回答1:

Changing the color with the CSS function of jQuery is not the best way, also it doesn't work as expected.

Better add a class to the specific TD:

"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
  if(aData.statusCode == "FAILED"){
    $("td:nth-child(2)", nRow).addClass("failed");
    $("td:nth-child(2)", nRow).removeClass("running");
  }
  if(aData.statusCode == "RUNNING"){
    $("td:nth-child(2)", nRow).removeClass("failed");
    $("td:nth-child(2)", nRow).addClass("running");
  }
}

The CSS would look like this:

td.failed {
  background-color: red;
}
td.running {
  background-color: green;
}

Edit

Added the :nth-child(2) selector the TD's.