我有一个由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
变量而不会在项目被删除后立即刷新整个页面。
答案 0 :(得分:2)
更改此行
$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 );
}
我没有对它进行过测试,但它应该有效。
答案 1 :(得分:0)
您可以按如下方式修改您的js:
$(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"
});
var ttlprice = parseInt( $(this).attr("rel"), 10 ); // item price
var $grand = $("#table2 > tr:last-child > td:last-child"); // grand total
$grand.text( parseInt( $grand.text(), 10 ) - ttlprice ); // subtracted
$(this).parent().parent().remove();
alert("Item has been deleted!");
}
return false;
});
});
你可以通过cyber_rookie建议在你的桌子上添加课程来简单地说明这一点,具体来说,
$output .='<td class="grand-total">'.$grand_total.'</td'>;
会使它成为
var ttlprice = parseInt( $(this).attr("rel"), 10 ); // item price
var $grand = $('.grand-total'); // grand total
$grand.text( parseInt( $grand.text(), 10 ) - ttlprice ); // subtracted