在我的 Web 應用程式中,我創建了表并從控制器為表分配了值。這里我想在表的末尾顯示列值Amount的總和。
所以到目前為止我已經這樣做了,但它沒有顯示總價值。
var tds = document.getElementById('PayvouchDt').getElementsByTagName('td');
var sum = 0;
for (var i = 0; i < tds.length; i ) {
sum = parseInt(tds[i].cells[3].innerHTML);
}
document.getElementById('PayvouchDt').innerHTML = '<tr><td>' sum '</td><td>Total Value</td></tr>';
<table class="table table-striped" id="PayvouchDt">
<thead>
<tr>
<th>#</th>
<th>Description</th>
<th>Cost Center</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
@{int RowNo = 0;} @for (int i = 0; i
< Model.First().PaymentVouchDetails.Count; i ) { <tr>
<td>@{RowNo ;} @RowNo</td>
<td>@Html.DisplayFor(Model => Model.First().PaymentVouchDetails[i].Details)</td>
<td>@Html.DisplayFor(Model => Model.First().PaymentVouchDetails[i].CostCenter)</td>
<td class="count-me">[email protected](Model => Model.First().PaymentVouchDetails[i].Amount)</td>
</tr>
}
</tbody>
</table>
uj5u.com熱心網友回復:
你需要行。細胞沒有細胞
還有一個數量通常有小數,所以我們需要它們作為浮點數而不是整數
var trs = document.getElementById('PayvouchDt').getElementsByTagName('tr');
var sum = 0;
for (var i = 0; i < trs.length; i ) {
sum = parseFloat(trs[i].cells[3].textContent);
}
document.getElementById('PayvouchDt').innerHTML = '<tr><td>' sum.toFixed(2) '</td><td>Total Value</td></tr>';
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Description</th>
<th>Cost Center</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="PayvouchDt">
<tr>
<td>1</td>
<td>Details</td>
<td>Costcenter</td>
<td class="count-me">1.50</td>
</tr>
<tr>
<td>2</td>
<td>Details</td>
<td>Costcenter</td>
<td class="count-me">3.20</td>
</tr>
</tbody>
</table>
我建議在轉換后的 textContent 上使用 tbody 和 reduce
const tds = document.querySelectorAll('#PayvouchDt tr td.count-me'); // or td:nth-child(4)
const sum = [...tds].map(td => td.textContent).reduce((a, b) => a b)
document.getElementById('PayvouchDt').innerHTML = `<tr><td>${sum.toFixed(2)}</td><td>Total Value</td></tr>`;
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Description</th>
<th>Cost Center</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="PayvouchDt">
<tr>
<td>1</td>
<td>Details</td>
<td>Costcenter</td>
<td class="count-me">1.50</td>
</tr>
<tr>
<td>2</td>
<td>Details</td>
<td>Costcenter</td>
<td class="count-me">3.20</td>
</tr>
</tbody>
</table>
uj5u.com熱心網友回復:
您可以簡單地使用 javascript [reduce 方法][1] 對陣列的元素求和。
例如
const myArray = [{value: 1, name: 'john'}, {value: 2, name: 'doe'}, {value: 3, name: 'john'}, {value: 4, name: 'doe'}];
const v = myArray.reduce((tot, el) => tot el.value, 0);
console.log(v)
您可以使用此代碼段并根據您的需要進行調整 [1]:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?retiredLocale= it
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/370019.html
標籤:javascript html
