【问题标题】:datatable ajax colour changing of rows based on condition in php基于php中条件的数据表ajax颜色变化
【发布时间】:2016-07-26 12:07:26
【问题描述】:

大家好,我有一个从 ajax 加载的数据表。
我需要根据某些条件更改行颜色。
像这样的脚本

 $(document).ready(function() {
        var dataTable =  $('#example').DataTable( {
            processing: true,
            serverSide: true,
            ajax: "ajax.php" // json datasource

        } );
  } );

这样的HTML

<table id="example" >
<thead>
<tr>
 <th>#</th>
 <th>ID</th>
 <th>Name</th>
 <th>Status</th>
</tr>
</thead>

</table>

在 ajax.php 中

while( $row=mysqli_fetch_array($query) ) {  // preparing an array
$nestedData=array();
$nestedData[] = $i;
$nestedData[] = $row["id"];
$nestedData[] = $row["name"];
$nestedData[] = $row["status"];
$data[] = $nestedData;
$i++;
}

$json_data = array(
"draw"            => intval( $requestData['draw'] ),   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal"    => intval( $totalData ),  // total number of records
"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data"            => $data   // total data array
);

echo json_encode($json_data);  // send data as json format

它有效,但我需要根据状态更改行颜色。
如果状态==1 然后黄色,如果状态==2 然后红色,如果状态==3 然后蓝色。我如何添加这个这种格式的表格行颜色。

【问题讨论】:

  • 数据表加载后,您可以使用每个循环函数并按每一行获取状态列值,并检查其列值并比较您的条件并满足然后更改颜色

标签: php mysql ajax datatable


【解决方案1】:

您需要按如下方式使用“fnRowCallback”:

$(document).ready(function() {
    var dataTable =  $('#example').DataTable({
        processing: true,
        serverSide: true,
        ajax: "ajax.php",
        "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
            if ( aData[3] == "1" )
            {
            $('td', nRow).css('background-color', 'Yellow');
            }
            else if ( aData[3] == "2" )
            {
            $('td', nRow).css('background-color', 'Red');
            }
            else if ( aData[3] == "3" )
            {
            $('td', nRow).css('background-color', 'Blue');
            }
        }
    });
});

【讨论】:

  • 如果我不需要显示状态而需要相同的结果怎么办?
  • 添加这个"columnDefs": [{ "visible": false, "targets": 3 }]
  • 感谢您的回答):
猜你喜欢
  • 2021-02-05
  • 1970-01-01
  • 2015-08-18
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多