我有一个使用 footerCallback 对每列求和的数据表。考虑到每列中的数据,这非常有效,但我还想添加更改每个单元格的求和值的功能。我尝试向这些单元格添加“contenteditable”,但进行更改不会影响页脚中的总和。
这是一个简单的jsfiddle,显示了我正在经历的行为:https://jsfiddle.net/rantoun/552y9j90/6/
HTML:
<table id="table1">
<thead>
<tr>
<th>Fruit</th>
<th># Eaten</th>
<th># Remaining</th>
</tr>
</thead>
<tfoot>
<tr>
<th align="right">Count</th>
<th align="left"></th>
<th align="left"></th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Apples</td>
<td contenteditable>3</td>
<td contenteditable>8</td>
</tr>
<tr>
<td>Oranges</td>
<td contenteditable>6</td>
<td contenteditable>5</td>
</tr>
<tr>
<td>Bananas</td>
<td contenteditable>2</td>
<td contenteditable>9</td>
</tr>
</tbody>
</table>
jQuery:
$("#table1").DataTable({
"paging": false,
"searching": false,
"info": false,
"footerCallback": function ( row, data, start, end, display ) {
var columns = [1, 2];
var api = this.api();
_.each(columns, function(idx) {
var total = api
.column(idx)
.data()
.reduce(function (a, b) {
return parseInt(a) + parseInt(b);
}, 0)
$('tr:eq(0) th:eq('+idx+')', api.table().footer()).html(total);
})
}
});
我还找到了 DataTables 编辑器 ( https://editor.datatables.net/examples/inline-editing/simple ),它非常适合这种情况 - 但它不是开源的。欢迎任何有关如何模仿此内联编辑功能的想法。我想避免使用模态来这样做。如有任何帮助,我们将不胜感激!
最佳答案
这是一个答案,允许您使用 contenteditable 进行就地编辑。
请注意,这需要 dataTables KeyTable plugin
/* Note - requires datatable.keys plugin */
var table = $("#table1").DataTable({
"keys": true,
"paging": false,
"searching": false,
"info": false,
"footerCallback": function ( row, data, start, end, display ) {
var columns = [1, 2];
var api = this.api();
_.each(columns, function(idx) {
var total = api
.column(idx)
.data()
.reduce(function (a, b) {
return parseInt(a) + parseInt(b);
}, 0)
$('tr:eq(0) th:eq('+idx+')', api.table().footer()).html(total);
})
}
});
// keys introduces the key-blur event where we can detect moving off a cell
table
.on( 'key-blur', function ( e, datatable, cell ) {
// The magic part - using the cell object, get the HTML node value,
// put it into the dt cell cache and redraw the table to invoke the
// footer function.
cell.data( $(cell.node()).html() ).draw()
} );
注意 - 我可以预见您可能会输入非数字数据。您必须在 key-blur 事件中对此进行监管,您可以在其中测试 dom 节点值并采取相应的操作。
关于javascript - 数据表页脚回调和内容可编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42125331/