我正在寻求以下帮助...
我有一个费用表,用户可以输入里程索赔和任何其他费用。例如,如果您在0-9英里之间旅行,则可以获得5英镑的固定费用,10-19英里可以获得7英镑,20-20英镑等等。
我有一个小计div,我希望每当里程值改变时更新,但我的计算小计的函数似乎在AJAX调用之前执行以使定价带完成。
小计功能基本上是:
function calculateClaim() {
var mileageDistance = document.getElementById('journeyMileage').value;
var expenseAmount1 = document.getElementById('expenseAmount1').value;
var expenseAmount2 = document.getElementById('expenseAmount2').value;
var expenseAmount3 = document.getElementById('expenseAmount3').value;
if (mileageDistance != "") {
calculateMileage = calculateMileageTotal(mileageDistance, function() {
var mileageTotal = this;
if (mileageTotal == '') {
$("#mileageTotal").val(0.00);
$("#journeyAmount").html('<strong>£0.00</strong>');
showDialog('alert','OK','','There is no mileage payment set up.','');
} else {
mileageTotal = parseFloat(mileageTotal).toFixed(2);
$("#mileageTotal").val(mileageTotal);
$("#journeyAmount").html('<strong>£' + mileageTotal + '</strong>');
}
});
} else {
mileageTotal = 0;
mileageTotal = mileageTotal.toFixed(2);
document.getElementById('journeyAmount').innerHTML = '<strong>£</strong>';
}
/*
SOME VALIDATION STUFF HERE FOR OTHER EXPENSE FIELDS
*/
subTotalCost = parseFloat(mileageTotal) + parseFloat(expenseAmount1) + parseFloat(expenseAmount2) + parseFloat(expenseAmount3);
subTotalCost = subTotalCost.toFixed(2);
document.getElementById('subTotal').innerHTML = '<strong>£' + subTotalCost + '</strong>';
}
调用的calculateMileageTotal函数如下:
function calculateMileageTotal(mileage,callback) {
var mileageDistance = mileage;
var mileageTariffExists = $('#mileageTariffExists').val();
if (mileageTariffExists == 1) {
$.ajax({
type: "POST",
url: "./ajaxQueries.cfc?method=getExpensesMileageBand",
data: ({
competitionID: $("#compID").val(),
matchDate: $("#matchDate").val(),
mileageTotal: mileageDistance
}),
dataType: "xml",
success: function(xml) {
$(xml).find('field').each(function(){
//alert((new XMLSerializer()).serializeToString(xml));
var mileageTotal = $(this).find('string').text();
callback.call(mileageTotal);
});
}
});
} else {
showDialog('alert','OK','','There is no Mileage Rate available.','');
}
}
getExpensesMileageBand函数肯定正常运行并返回里程率,但它是认为mileageTotal值为空的子总计算,因为它还没有从函数返回但是如果我在那里放了几个警报工作(因为它减慢了功能)。
有人有任何想法吗?我之前没有使用过回调,所以我不确定这是不是我错了?
答案 0 :(得分:0)
为什么不将小计计算作为一个单独的函数,从回调的结尾或else语句的结尾调用。
function calculateSubtotal(milageTotal) {
subTotalCost = parseFloat(mileageTotal) + parseFloat(expenseAmount1) + parseFloat(expenseAmount2) + parseFloat(expenseAmount3);
subTotalCost = subTotalCost.toFixed(2);
document.getElementById('subTotal').innerHTML = '<strong>£' + subTotalCost + '</strong>';
}
if (mileageDistance != "") {
calculateMileage = calculateMileageTotal(mileageDistance, function() {
var mileageTotal = this;
if (mileageTotal == '') {
// existing code
} else {
// existing code
calculateSubtotal(milageTotal);
}
});
} else {
// existing code
calculateSubtotal(milageTotal);
}