【发布时间】:2016-11-12 22:25:42
【问题描述】:
我有一个要在 html 表中显示的数据。数据来自使用 ajax 请求的 3rd 方服务器(php)。使用以下代码可以很好地显示数据: HTML:
<table id="tbl-product">
<tr>
<th>product</th>
<th>date</th>
<th>quantity</th>
<th>cost</th>
</tr>
</table>
成功时将显示数据中的 ajax 调用 (success: function(data, status, jqXHR){):
data.forEach(function(row) {
var productname = row.uproducts_product;
var productico = productname.replace(/\s+/g, "-") + '.png';
var productcost = row.uproducts_total_investment;
var str = '<tr>';
str += '<td>' + '<img class="product_icon" src="images/products/icon-'+ productico +'">' + '<div class="productname">'+ row.uproducts_product + '</div></td>';
str += '<td><div class="textinfo ">' + row.date + '<br/><span class="date">' + row.uproducts_date + '</span></div> </td>';
str += '<td><span class="textinfo">' + row.uproducts_quantity + '</span></td>';
str += '<td><span class="textinfo">' + productcost + '</td>';
str += '</tr>';
$('#tbl-product').append(str);
});
所以,项目是这样显示的
产品 | 日期 | 数量 | 费用
一个 | 12-01-2015 | 2 | 2,100
B | 01-04-2016 | 4 | 5,300
但在产品项目下方,我想添加一行自动计算总数量和总成本。示例:
产品 | 日期 | 数量 | 费用
一个 | 12-01-2015 | 2 | 2,100.00
B | 01-04-2016 | 4 | 5,300.00
总计 | 6(数量)| 7,400.00(成本)
Updated1 Alternatives:我在这里创建了一个替代方案,我在数组中添加了一个变量来计算总和,服务器将其作为 json 数据响应。 所以数据现在看起来像这样:
[{
"id":"11",
"user_id":"8000",
"product":"Shoes A",
"quantity":"1",
"open":"2015-01-04",
"investment":"3000"
},
{
"id":"12",
"user_id":"8000",
"product":"Shoes B",
"quantity":"1",
"date":"2015-03-01",
"cost":"1500"
},
{
"total_qty":"2"
"total_cost":"4500"
}]
那么,如果我使用这种方法,是否更容易将其作为一行附加到产品项下方?怎么样?
【问题讨论】: