来自JSON响应的DataTable类

时间:2018-08-06 11:15:25

标签: jquery datatable datatables

我正在尝试从json(API)向该单元格添加一个类,但这会呈现:

<td class="status_id">active</td>

代替<td class="up">active</td>

这是我到目前为止尝试过的:

var dataSet= [{
    "id": 1,
    "name": "Mario Bros",
    "timestamp": 1533552555,
    "status": "active",
    "status_id": "up"
  }, {
    "id": 2,
    "name": "Luigi Bros",
    "timestamp": 1533552556,
    "status": "inactive",
    "status_id": "dw"
  }
];

$('table').DataTable({
  data:dataSet,
  columns: [
      {data:"id"},
      {data:"name"},
      {data:"timestamp"},
      {data:"status",class:"status_id"}
  ],
  processing:false,paging:true,searching:false,ordering:true,info:false,paging:false
});
table{width:100%}
td{border:1px solid #000;width:25%}
.dw{background:red;color:#FFF}
.up{background:green;color:#FFF}
<link href="//cdn.datatables.net/v/bs4/dt-1.10.18/datatables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/v/bs4/dt-1.10.18/datatables.min.js"></script>
<table></table>

2 个答案:

答案 0 :(得分:1)

我会使用createdCell

columns: [
  { data: "id" },
  { data: "name" },
  { data: "timestamp" },
  { data: "status",
    createdCell: function( cell, cellData, rowData) {
       $(cell).addClass(rowData.status_id)
    }
  }
]

http://jsfiddle.net/cxg1875r/

答案 1 :(得分:0)

它可与以下代码一起使用,但我认为这不是最好的解决方案。

var dataSet= [{
    "id": 1,
    "name": "Mario Bros",
    "timestamp": 1533552555,
    "status": "active",
    "status_id": "up"
  }, {
    "id": 2,
    "name": "Luigi Bros",
    "timestamp": 1533552556,
    "status": "inactive",
    "status_id": "dw"
  }
];

$('table').DataTable({
  data:dataSet,
  columns: [
      {data:"id"},
      {data:"name"},
      {data:"timestamp"},
      {data:"status"}
  ],
  rowCallback: function(row, data, index) {
    $('td:eq(3)', row).addClass(data.status_id);
  },
  processing:false,paging:true,searching:false,ordering:true,info:false,paging:false
});
table{width:100%}
td{border:1px solid #000;width:25%}
.dw{background:red;color:#FFF}
.up{background:green;color:#FFF}
<link href="//cdn.datatables.net/v/bs4/dt-1.10.18/datatables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/v/bs4/dt-1.10.18/datatables.min.js"></script>
<table></table>