我想用datatables将两列相乘。我的桌子是这样的:
<table border="5" class="teste1" method="POST" id="table">
<thead>
<tr>
<th class="filter" style="width:42px; text-align: center; font-size: 12px">Quantidade</th>
<th class="filter" style="width:25px; text-align: center; font-size: 12px">Preço</th>
</tr>
</thead>
<tbody>
<tr>
<?php
while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {
?>
<td style="font-size: 12px"> <?php echo $rows_cursos['Quantidade']; ?></td>
<td style="font-size: 12px"> <?php echo $rows_cursos['Preco']; ?></td>
</tr>
<?php } ?>
</tbody>';
<?php
}
?>
</table>
然后,我尝试将quantity * price
的列乘以如下:
(function ($) {$(document).ready(function () {
$('#table').dataTable({
drawCallback: function () {
var api = this.api();
$( api.table().footer() ).html(
api.column( 1 * 2 ).data().sum()
);
}
});
})(jQuery)
但是它不起作用,我想在<tfoot> </ tfoot>
表的表底部一行显示数据。我希望这个乘法的总和总是根据过滤器返回结果。
答案 0 :(得分:2)
我想,您已经用PHP脚本准备了HTML(我认为这不是最好的选择)。
但是,如果您在<tfoot>
中保留了一些节点以显示总费用(例如,将其设为span#sumproduct
),您可以:
{search:'applied'}
和rows().data()
.toArray()
选择器修饰符)行进入数组
span#sumproduct
.text()
(footerCallback
选项):
//source data
const srcData = [['apple',5,3],['pear',4,2],['banana',3,1]]
//datatables initialization
$('#example').DataTable({
dom: 'ft',
data: srcData,
columns: ['item', 'qty', 'price'].map(title => ({title})),
footerCallback: function(){
const sumProduct = this
.api()
.rows({search:'applied'})
.data()
.toArray()
.reduce((res,[item, qty, price]) => res += qty*price, 0);
$('#sumproduct').text(sumProduct);
}
})
<!doctype html><html><head><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.css" /><script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.js"></script></head><body><table id="example"><tfoot><tr><td colspan="3">Overall cost is: <span id="sumproduct"></span></td></tr></tfoot></table></body></html>