[英]jQuery calculation in table td loop
我通过 PHP 获取 JSON 数据。 我试图在 javascript 和 jQuery 的帮助下计算td
的值,并计算如下表示例的期初余额和期末余额。
这有可能吗? 请帮助我如何在我的 jQuery 代码中使用 jquery 实现。
示例表 -
open bal as 0 first time
+ today in
- today out
= closing bal
和previous closing bal
将在open bal next day
。
公开赛 | 今天在 | 今天出去 | 闭幕式 |
---|---|---|---|
1 | 1 | 1 | 1 |
2 | 0 | 1 | 1 |
0 | 2 | 0 | 2 |
$.ajax({ type: "POST", cache: false, }, success: function(response) { if (response == "ok") { $.each(response.data, function(i, items) { tableWithHeader.find('tbody').append(` <tr> <td>0</td> <td>${items.inqty}</td> <td>${items.outqty}</td> <td></td> </tr> `); }); } });
这里:
$.ajax({
type: "POST",
cache: false,
},
success: function(response) {
if (response == "ok") {
let openqty = 0 // declare outside of loop
let closeqty = 0 // declare outside of loop
$.each(response.data, function(i, items) {
closeqty = parseInt(items.inqty) - parseInt(items.outqty) + openqty
//calculate closeqty
tableWithHeader.find('tbody').append(`
<tr>
<td>${openqty}</td> // this will be 0 on first run
<td>${items.inqty}</td>
<td>${items.outqty}</td>
<td>${closeqty}</td>
</tr>
`);
});
openqty = closeqty // now set it for next loop to be same as closeqty
}
});
工作示例:
//$.ajax({ //type: "POST", //cache: false, //}, //success: function(response) { //if (response == "ok") { let openqty = 0 // declare outside of loop let closeqty = 0 // declare outside of loop const response = { data: [{ inqty: "2", outqty: "0" }, { inqty: "0", outqty: "1" }, { inqty: "1", outqty: "1" }] } // sample data $.each(response.data, function(i, items) { closeqty = parseInt(items.inqty) - parseInt(items.outqty) + openqty //calculate closeqty $("table").find('tbody').append(` <tr> <td>${openqty}</td> // this will be 0 on first run <td>${items.inqty}</td> <td>${items.outqty}</td> <td>${closeqty}</td> </tr> `); openqty = closeqty // now set it for next loop to be same as closeqty });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody> </tbody> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.