问题
I am trying to make a conditional statement which will replace data not only to the column that I target but also and on a second one based of selected target's value.
setTimeout(function() {
$('#invoices-table').DataTable({
responsive: true,
columnDefs: [{ orderable: false, targets: [-1, -2, -3] }, {
targets: 0, // statement is based on first column data
render: function(data, type) {
// if data in col0 is "1" then replace data in col0 and col5 (pay button)
if (type == 'display' && data == '1') {
return [
{ data: '<i class="fa fa-3 fa-check-circle-o datatable-paid-1"></i>', target: 0 },
{ data: '<button class="pay-btn btn btn-sm btn-success disabled">Paid</button>', target: 5 }
]
} else {
return [
{ data: '<i class="fa fa-3 fa-exclamation-circle datatable-paid-0"></i>', target: 0 }
]
}
},
}],
"lengthMenu": [
[100, 5, 25, 50, -1],
[100, 5, 25, 50, "All"]
],
dom: 'Bfrtip',
initComplete: function() {
var api = this.api();
// my actions upon complete
}
});
}, 1500); // delay is needed due to needed time of mySQL for passing results
https://codepen.io/anon/pen/jmgBdv?editors=0010
EDIT
Updated code both on post and codepen due to wrong target numbers
回答1:
If you look at column.render as suggested in previous answer, then you will see that the render
callback have a few more params :
render: function ( data, type, full, meta ) {
Each section in columnDefs
can have multiple targets, but targets
is referring to column indexes, not data! So you have got this a little bit wrong. The meaning is : You can pass the same result string to multiple columns, i.e handling columns with for example checkboxes in one callback - but not distinguish between targets (columns) and different return strings in the same columnDefs
section. That would not make so much sense, and would be really hard to implement.
Logically, if you want different values for different columns, then use different columnDefs
sections. The full
param hold all values for the row, so even you are targeting column #14 you can use full
to inspect the value of column #0. Here is what you should do :
columnDefs: [
{ orderable: false, targets: [-1, -2, -3] },
{ targets: 0,
render: function(data, type) {
if (type == 'display') {
return data == '1'
? '<i class="fa fa-3 fa-check-circle-o datatable-paid-1"></i>'
: '<i class="fa fa-3 fa-exclamation-circle datatable-paid-0"></i>'
} else {
return data
}
}
},
{ targets: 14,
render: function(data, type, full) {
if (type == 'display') {
return full[0] == '1'
? '<button class="pay-btn btn btn-sm btn-success disabled">Paid</button>'
: '<button class="pay-btn btn btn-sm btn-success">pay</button>'
} else {
return data
}
}
}
]
来源:https://stackoverflow.com/questions/44282088/datatables-data-replacement-to-multiple-columns-based-on-ones-value