【发布时间】:2014-07-26 16:18:58
【问题描述】:
我有一个简单的应用程序,可以计算表中所有行的总价格。
像这样添加新行:
function add() {
[...data removed for readability...]
jQuery.ajax({
type: "POST",
data: {
a:'addadminprice',
id:<? echo $id; ?>,
priceid:el.attr('value'),
price:price
},
url: options.actionurl,
dataType: "json",
success: function(result){
if (result.status=='success') {
var initaddprice = 0;
var row="<tr class='pricedata' rel='"+result.id+"'>";
row+="<td class='drag'>::::</td>";
row+="<td>"+el.text()+"</td>";
row+="<td class='right'>"+price+"</td>";
row+="<td><input type='text' onchange='recalc(this,"+result.id+")' value='"+price+"' /></td>";
row+="<td>"+(el.data('percent')=='1'?"%":"")+"</td>";
row+="<td><input type='text' onchange='recalc(this,"+result.id+")' value='"+result.qty+"' /></td>";
row+="<td class='right'>"+initaddprice.toFixed(3)+"</td>";
row+="<td><a class='button' href='#' onclick='return removeprice(this,"+result.id+")'>remove</a></td>";
row+="</tr>";
var isfound=false;
$('.pricedata').last().after($(row));
el.remove();
changePrice();
recalcall();
setsort();
saveposition();
}
}
});
如您所见,它添加了行 - 然后根据所有行重新计算总数。到目前为止一切顺利,效果很好。
function recalcall() {
console.clear();
console.log('----start calculation----');
var total=0;
$('.pricedata').each(function(){
var price=parseFloat($(this).find('td').eq(6).text());
if (isNaN(price)) price=0;
total+=price;
console.log('+'+price+' = '+total);
});
console.log('----end calculation----');
$('#total').text(total.toFixed(3));
}
当我删除一行时,它会删除元素并重新计算总数。但不幸的是,该行仍然包含在计算过程中?我在这里不知所措。一旦你删除了一个元素,就应该考虑到它,对吧?
function removeprice(el,id) {
if (confirm('Are you sure?')) {
jQuery.ajax({
type: "POST",
data: {
a:'deleteprojectprice',
id:id
},
url: options.actionurl,
dataType: "json",
success: function(result){
if (result.status=='success') {
$(el).closest('tr').remove();
}
}
});
}
recalcall();
}
【问题讨论】:
-
当您已经在成功功能中时,您不必询问 result.status。它是成功的事实是你如何进入那个回调函数:)
标签: javascript jquery ajax html-table