我有DataTable,第一列是sl no,我想使其自动成为序列号1,2,3,4...。我希望id列应该自动递增。
{ data: "id", title: "Sl. No." }
$('#myTable').DataTable({
columnDefs: [
{
"targets": [0, 1, 2, 3, 4, 5], // your case first column
"className": "text-center",
}
],
"bDestroy": true,
"scrollX": true,
data: dataSet,
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
],
columns: [
{ data: "id", title: "Sl. No." },
{
"data": "updatedDate", title: "Time", render: function (data, type, row) {
return moment(row.updatedDate).format('DD/MM/YYYY hh:mm:ss A');
}
},
{ data: "voltage", title: "Voltage" }
],
order:[0,"desc"]
});
答案 0 :(得分:1)
下面是一个示例,该示例使用columnDefs
及其渲染option
将序列号添加到数据表中
var dataSet = [{"name":"Wade Rodriguez","age":21},{"name":"Maxwell Rush","age":31},{"name":"Ruiz Murray","age":40},{"name":"Tanner Crosby","age":37},{"name":"Shelby Douglas","age":25},{"name":"Haney Fulton","age":35}]
$(document).ready(function() {
$("#myTable").DataTable({
data: dataSet,
"columns": [{
"title": "Sl. No."
},
{
"data": "name",
"title": "Name"
},
{
"data": "age",
"title": "Age"
}
],
"columnDefs": [{
"render": function(data, type, full, meta) {
dataSet[meta.row].id = meta.row + 1; // adds id to dataset
return meta.row + 1; // adds id to serial no
},
"targets": 0
}],
});
console.log(dataSet)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="myTable" class="display" cellspacing="0" width="100%">
</table>