這里有張桌子:
<table style="width:920px;" id="tblPotrawySkladniki">
<thead>
<tr>
<td class="cell0 style1"><p style="font-style:italic;">Nazwa produktu</p></td>
<td class="cell1 style1"><p style="font-style:italic;">Waga [g]</p></td>
</tr>
</thead>
<tbody>
<tr>
<td>banana</td>
<td>10</td>
</tr>
<tr>
<td>orange</td>
<td>20</td>
</tr>
<tr>
<td>raspberry</td>
<td>35</td>
</tr>
</tbody>
<tfoot>
<tr>
<td class="cell0 style1"><p style="font-weight:bold;">TOTAL</p></td>
<td class="cell1 style1"><p style="font-weight:bold;"></p></td>
</tr>
</tfoot>
</table>
如何總結 tbody 第二列中的所有單元格并將結果放在第二列中的 tfoot 單元格中?
該表是動態的。我想使用jquery。
uj5u.com熱心網友回復:
這將是一種方法:
let sum=$("#tblPotrawySkladniki tbody td:nth-child(2)").get().reduce((a,c)=>
$(c).text().replace(",",".") a,0);
$("#tblPotrawySkladniki tfoot td:nth-child(2)").text(sum);
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<table id="tblPotrawySkladniki">
<thead>
<tr>
<td class="cell0 style1"><p style="font-style:italic;">Nazwa produktu</p></td>
<td class="cell1 style1"><p style="font-style:italic;">Waga [g]</p></td>
</tr>
</thead>
<tbody>
<tr>
<td>banana</td>
<td>10</td>
</tr>
<tr>
<td>orange</td>
<td>20,3</td>
</tr>
<tr>
<td>raspberry</td>
<td>35,5</td>
</tr>
</tbody>
<tfoot>
<tr>
<td class="cell0 style1"><p style="font-weight:bold;">TOTAL</p></td>
<td class="cell1 style1"><p style="font-weight:bold;"></p></td>
</tr>
</tfoot>
</table>
而不是parseInt()我的腳本使用帶有一元運算子的隱式型別轉換 before $(c).text()。
uj5u.com熱心網友回復:
您可以使用 jQuery .each() 回圈遍歷每行的第二個 td,使用 $(this).text() 訪問元素的內容,然后隨時添加它們。您應該首先決議該值,以便它們將作為數字相加而不是連接。
let values = 0;
jQuery('table tbody tr td:nth-of-type(2)').each(function(){
let value = parseInt($(this).text(),10);
values = value;
});
console.log(values);
uj5u.com熱心網友回復:
<table style="width:920px;" id="tblPotrawySkladniki">
<thead>
<tr>
<td class="cell0 style1">
<p style="font-style:italic;">Nazwa produktu</p>
</td>
<td class="cell1 style1">
<p style="font-style:italic;">Waga [g]</p>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>banana</td>
<td> 10</td>
</tr>
<tr>
<td>orange</td>
<td> <span class='price'>20</span></td>
</tr>
<tr>
<td>raspberry</td>
<td> <span class='price'>35</span></td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="2" style="text-align:center"><span id="sum"></span></th>
</tr>
</tfoot>
$(document).ready(function() {
$('.price').each(function(i) {
calculateColumn(i);
});
});
function calculateColumn(index) {
var total = 0;
$('table tr').each(function() {
var value = parseInt($('.price', this).eq(index).text());
if (!isNaN(value)) {
total = value;
}
});
$('#sum').eq(index).text('Total: ' total);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/438242.html
上一篇:無法在js檔案中指定影像路徑
