我生成多个表,结构相同但值不同,并在 php/mysql 中循环。我有一个脚本来汇总所有值并显示结果,但仅当值位于同一行时才有效。我只需要对“precio”列进行求和。
这是一个 HTML。这是表的结构:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('tr').each(function () {
var sum = 0
$(this).find('.precio').each(function () {
var precio = $(this).text();
if (!isNaN(precio) && precio.length !== 0) {
sum += parseFloat(precio);
}
});
$('.total_prt', this).html(sum);
});
});
</script>
<table class="table table-striped">
<thead>
<tr>
<th width="70%">Descripción</th>
<th width="20%">Precio</th>
</tr>
</thead>
<tbody>
<tr>
<td>Display</td>
<td class="precio">1300</td>
</tr>
<tr>
<td>Keyboard</td>
<td class="precio">300</td>
</tr>
<tr>
<td><b>Total:</b></td>
<td class="total_prt"><b>$</b></td>
</tr>
</tbody>
</table>
<br>
<table class="table table-striped">
<thead>
<tr>
<th width="70%">Descripción</th>
<th width="20%">Precio</th>
</tr>
</thead>
<tbody>
<tr>
<td>HDD</td>
<td class="precio">400</td>
</tr>
<tr>
<td>System</td>
<td class="precio">425</td>
</tr>
<tr>
<td>Something</td>
<td class="precio">350</td>
</tr>
<tr>
<td><b>Total:</b></td>
<td class="total_prt"><b>$</b></td>
</tr>
</tbody>
</table>
最佳答案
您需要分别循环遍历所有表,并在表行循环外部而不是内部初始化 sum
。
$(document).ready(function() {
$('.table').each(function() {
var sum = 0
$(this).find('tr').each(function() {
$(this).find('.precio').each(function() {
var precio = $(this).text();
if (!isNaN(precio) && precio.length !== 0) {
sum += parseFloat(precio);
}
});
$('.total_prt', this).html(sum);
});
})
});
<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="70%">Descripción</th>
<th width="20%">Precio</th>
</tr>
</thead>
<tbody>
<tr>
<td>Display</td>
<td class="precio">1300</td>
</tr>
<tr>
<td>Keyboard</td>
<td class="precio">300</td>
</tr>
<tr>
<td><b>Total:</b></td>
<td class="total_prt"><b>$</b></td>
</tr>
</tbody>
</table>
<br>
<table class="table table-striped">
<thead>
<tr>
<th width="70%">Descripción</th>
<th width="20%">Precio</th>
</tr>
</thead>
<tbody>
<tr>
<td>HDD</td>
<td class="precio">400</td>
</tr>
<tr>
<td>System</td>
<td class="precio">425</td>
</tr>
<tr>
<td>Something</td>
<td class="precio">350</td>
</tr>
<tr>
<td><b>Total:</b></td>
<td class="total_prt"><b>$</b></td>
</tr>
</tbody>
</table>
关于php - 使用 JQuery 求和列值以获取多个表中的总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42275558/