gpt4 book ai didi

php - jQuery 中删除一项后计算一张动态表的总和

转载 作者:行者123 更新时间:2023-11-29 08:26:18 27 4
gpt4 key购买 nike

我有一个由 PHP 代码生成的动态表:

   $grand_total=0;
$sql1=mysql_query("SELECT * FROM cart")
while($row=mysql_fetch_array($sql1)){

$id=$row['id'];
$unit_price=$row['unit_price'];
$qty=$row['qty'];

$total_price=$unit_price*$qty;
$grand_total=$grand_total+$total_price;

$output .='<tr id="$id">';
$output .='<td>'.$unit_price.'</td>';
$output .='<td>'.$qty.'</td>';
$output .='<td>'.$total_price.'</td>';
$output .='<td align="center"><img class="delete" src="images/Erase.png" alt="" width="16" height="16" rel="'.$total_price.'" /></td>';
$output .='</tr>';

}
$output .='<tr>';
$output .='<td colspan="2"> TOTAL </td>';
$output .='<td>'.$grand_total.'</td'>;
$output .='</tr>';

当用户点击图像删除一项时,它会调用 jQuery 函数:

<script>
$(document).ready(function(){
$('#table2 td img.delete').click(function(){
if (confirm("Do you want to delete this item?")) {

var parent = $(this).closest('TR');
var id = parent.attr('id');
$.ajax({
type: "POST",
data: "id=" +id,
url: "packages_cart_delete.php"
});
$(this).parent().parent().remove();
alert("Item has been deleted!");
}
return false;

});
});

</script>

HTML 输出:

<table id="table2" width="100%" border="0" cellspacing="3" cellspadding="3">
<tr>
<th>Unit Price</th>
<th>Qty</th>
<th>Total Price</th>
<th>Delete</th>
</tr>
<?php echo $output; ?>
</table>

它运行得非常好。唯一缺少且我无法解决的问题是如何自动计算 $grand_total 变量,而无需在删除项目后立即刷新整个页面。

最佳答案

更改此行

      $output .='<td>'.$total_price.'</td>';

      $output .='<td class="total-price">'.$total_price.'</td>';

并改变

   $output .='<td>'.$grand_total.'</td'>;

   $output .='<td class="grand-total">'.$grand_total.'</td'>;

并在删除成功后调用以下函数:

function calculateTotal() {
var grandTotal = 0;
$(".total-price").each( function() {
var thisPrice = parseInt( $(this).text() );
grandTotal += thisPrice;
});
$(".grand-total").text( grandTotal );
}

我还没有测试过,但它应该可以工作。

关于php - jQuery 中删除一项后计算一张动态表的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17826114/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com