datatables

datatables - Tablas de datos: cambie el color de la celda según los valores



(1)

Estoy usando DataTable para crear una tabla interactiva. Tengo 9 columnas, 5 de las cuales son valores. Quiero cambiar el color de fondo de cada celda según su específico.

Comencé tratando de cambiar el color completo de la fila primero, ya que parecía una tarea más fácil. Sin embargo, no puedo cambiar nada.

Mi código está abajo:

<head> <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.13/css/jquery.dataTables.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.js"></script> <script> $(document).ready(function(){ $(''#countryTable'').DataTable(); }); </script> <script> $(document).ready( function () { $(''#countryTable '').DataTable({ "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { if ( aData[3] > 11.7 ) { $(nRow).css(''color'', ''red'') } else if ( aData[2] == "4" ) { $(nRow).css(''color'', ''green'') } } }); </script> </head> <body> <table id ="countryTable" class="display" cellspacing="0" data-page-length=''193''> <thead> <tr> <th>Rank</th> <th>Country</th> <th>Code</th> <th>Total</th> <th>Beer</th> <th>Wine</th> <th>Spirits</th> <th>Other</th> <th>Score</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Estonia</td> <td>EE</td> <td>14.97</td> <td>5.87</td> <td>1.65</td> <td>5.64</td> <td>1.81</td> <td>3 - Medium Risky</td> </tr> <tr> <td>2</td> <td>Belarus</td> <td>BY</td> <td>14.44</td> <td>2.5</td> <td>0.75</td> <td>6.73</td> <td>4.46</td> <td>4 - Very Risky</td> </tr> </tbody>

También intenté usar la siguiente función, pero no tuve suerte. Si alguien pudiera ayudar, sería muy apreciado, ya que estoy muy interesado en el script java.

$(document).ready( function () { $(''#countryTable'').DataTable({ "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { if ( aData[3] == "5" ) { $(''td'', nRow).css(''background-color'', ''Red''); } else if ( aData[3] == "4" ) { $(''td'', nRow).css(''background-color'', ''Orange''); } } });


En primer lugar, inicialice DataTable solo una vez. Luego, según su pregunta, use rowCallback y no fnRowCallBack como se muestra a continuación:

var oTable = $(''#countryTable'').DataTable({ ''rowCallback'': function(row, data, index){ if(data[3]> 11.7){ $(row).find(''td:eq(3)'').css(''color'', ''red''); } if(data[2].toUpperCase() == ''EE''){ $(row).find(''td:eq(2)'').css(''color'', ''blue''); } } });

Aquí hay un fiddle