简体   繁体   中英

Datatables change color background

I'm developing a table based on Datatables with server side process.

I want to change the background color for each cell if the value is different from the previous row in the same cell position

This is my output table generated with server side process:

<table>
    <tr>
        <td>Acer computer</td>
        <td>Ram 32 gb</td>
        <td>$500</td>
    </tr>
    <tr>
        <td>Acer computer</td>
        <td>Ram 32 gb</td>
        <td>$500</td>
    </tr>
    <tr>
        <td>Acer computer</td>
        <td>Ram 16 gb</td>
        <td>$320</td>
    </tr>
</table>

I want to change the background color of the TD for the second TR because the value changed.

I tryed with createdCell but with bad results.

https://datatables.net/reference/option/columns.createdCell

Is possible with datatables? Is there a jsfiddle available for help?

I'm assuming that you have a way to check if the state of the value has changed. What I suggest is to set data attribute in the cell as the example below and then use css to change the color.

<table>
<tr>
    <td>Acer computer</td>
    <td>Ram 32 gb</td>
    <td>$500</td>
</tr>
<tr>
    <td data-changed='true'>Acer computer</td>
    <td>Ram 32 gb</td>
    <td>$500</td>
</tr>
<tr>
    <td>Acer computer</td>
    <td>Ram 16 gb</td>
    <td>$320</td>
</tr>
</table>

Try this,
Edit this code with your database values
by using your html code, i have done a simple solution with jQuery
using .each() function

 $(document).ready(function(){
    var n=1;
    var j=0;
    var prev_val = function(eq_no){
    return  $('table tr:eq('+eq_no+') td:last').text();
   }
  $('table tr').each(function(){
         var index_val = $('table tr').index($(this));
     var fill_val = $(this).find('td:last').text();
     if(index_val == n){
        if(fill_val == prev_val(j)){

        }
        else{
        $(this).find('td:last').css({"background":"#0d0d0d"});
        }
        n++;
            j++;  

      }
    });
});

try this fiddle

https://jsfiddle.net/saifudazzlings/s05u3th0/1/

Solved with Datatables API here the code:

"columnDefs": [ {
    "targets": [1,2,3,4,5,6,7,8,9,10,11,12,13,14],
    "createdCell": function (td, cellData, rowData, row, col) {
        if (row > 0) {
            old = table.data(row - 1);
            if ( cellData != old.row(row).column(col).data()[row-1] ) {
                previous_row = old.row(row).column(col).nodes()[row-1]
                $(previous_row).css('background-color', '#FFFF99')
            }
        }
    }
    } ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM