2
我有幾個具有相同結構的表。它對價格有不同的價值。我想獲得價格欄的運行餘額。所以我想獲得總和並在運行平衡列中打印每個迭代。例如。在價格欄中,我有400,425和350,所以在運行平衡欄中,我應該有400,825,1175。目前,我只能得到總和。使用JQuery獲取多個表的運行餘額
這裏是我的html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<table class="table table-striped">
<thead>
<tr>
<th width="60%">Item</th>
<th width="20%">Price</th>
<th width="20%">Running Balance</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bacon</td>
<td class="price">1300</td>
<td class="runningBal"></td>
</tr>
<tr>
<td>Pancakes</td>
<td class="price">300</td>
<td class="runningBal"></td>
</tr>
<tr>
<td><b>Total:</b></td>
<td class="total"><b>$</b></td>
<td class="totalBal"></td>
</tr>
</tbody>
</table>
<br>
<table class="table table-striped">
<thead>
<tr>
<th width="60%">Item</th>
<th width="20%">Price</th>
<th width="20%">Running Balance</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fries</td>
<td class="price">400</td>
<td class="runningBal"></td>
</tr>
<tr>
<td>Nuggets</td>
<td class="price">425</td>
<td class="runningBal"></td>
</tr>
<tr>
<td>Ice Cream</td>
<td class="price">350</td>
<td class="runningBal"></td>
</tr>
<tr>
<td><b>Total:</b></td>
<td class="total"><b>$</b></td>
<td class="totalBal"></td>
</tr>
</tbody>
</table>
這裏是我的javascript
$('.runningBal').each(function() {
var sum = 0;
$(this).parents('table').find('.price').each(function() {
var floted = parseFloat($(this).text());
if (!isNaN(floted)) sum += floted;
$('.runningBal').html(sum);
})
//$(this).html(sum);
});
這裏是fiddle
你如何生成這些表。 ?您應該計算運行平衡並將其放置在表格渲染過程中。 – Panther
我使用PHP生成帶foreach的表格,但我只在這裏顯示一個較不復雜的版本 –
然後,當您遇到價格時,應將其存儲在變量中並回顯在運行平衡列。簡單地說,如果你沒有對客戶端的價格做任何改變,邏輯最好放在php方面。 – Panther