我有一个计算价格的功能。变量totalPrice
计算选择的总和。然后我将totalPrice
写入div。
我的问题是我在正在运行更改事件,我正在尝试在更改事件中运行calcTotalPrice
函数,然后尝试访问totalPrice
变量,但它给了我变量未定义错误。
如何从我的函数中获取调整后的totalPrice
变量并在事件中运行它?
function calcTotalPrice() {
var totalPrice = 0;
var discountPrice = 0;
if (package1.is(':checked') && package2.is(':checked')) {
$('.calendar-check:checked').each(function () {
var calSoloPrice = ($(this).data('solo-price'));
var calCombinedPrice = ($(this).data('combined-price'));
totalPrice += parseInt($(this).data('combined-price'));
discountPrice += calSoloPrice - calCombinedPrice;
});
$('.tp-pack-check:checked').each(function () {
var tpSoloPrice = ($(this).data('solo-price'));
var tpCombinedPrice = ($(this).data('combined-price'));
totalPrice += parseInt($(this).data('combined-price'));
discountPrice += tpSoloPrice - tpCombinedPrice;
});
$('#package-review-savings').html("<div class='discountMed'>You will be saving $" + discountPrice + " per order by bundling your product package.</div>");
}
else {
if (package1.is(':checked')) {
$('.calendar-check:checked').each(function () {
totalPrice += parseInt($(this).data('solo-price'));
});
}
if (package2.is(':checked')) {
$('.tp-pack-check:checked').each(function () {
totalPrice += parseInt($(this).data('solo-price'));
});
}
}
$('#package-review-total').html("$" + totalPrice);
};
$('body').on('change', function () {
calcTotalPrice();
console.log("Total Price" + totalPrice);
});
答案 0 :(得分:1)
您已在函数内定义了变量。然后它只存在于该范围内。
如果从定义中删除var
,则可以全局访问(尽管我强烈建议不要这样做)。
更好的策略是你的函数返回计算值:
function calcTotalPrice() {
var totalPrice = 0;
var discountPrice = 0;
if (package1.is(':checked') && package2.is(':checked')) {
$('.calendar-check:checked').each(function () {
var calSoloPrice = ($(this).data('solo-price'));
var calCombinedPrice = ($(this).data('combined-price'));
totalPrice += parseInt($(this).data('combined-price'));
discountPrice += calSoloPrice - calCombinedPrice;
});
$('.tp-pack-check:checked').each(function () {
var tpSoloPrice = ($(this).data('solo-price'));
var tpCombinedPrice = ($(this).data('combined-price'));
totalPrice += parseInt($(this).data('combined-price'));
discountPrice += tpSoloPrice - tpCombinedPrice;
});
$('#package-review-savings').html("<div class='discountMed'>You will be saving $" + discountPrice + " per order by bundling your product package.</div>");
}
else {
if (package1.is(':checked')) {
$('.calendar-check:checked').each(function () {
totalPrice += parseInt($(this).data('solo-price'));
});
}
if (package2.is(':checked')) {
$('.tp-pack-check:checked').each(function () {
totalPrice += parseInt($(this).data('solo-price'));
});
}
}
$('#package-review-total').html("$" + totalPrice);
return totalPrice;
};
$('body').on('change', function () {
var totalPrice = calcTotalPrice();
console.log("Total Price" + totalPrice);
});