我正在创建一个简单的送餐服务。我正在尝试找出选择小费时如何更新总金额
if(choiceRegular.checked == true) {
var totalPrice = choiceRegular.value;
}else if (choicePremium.checked == true) {
totalPrice = choicePremium.value;
}else if(choiceRoyal.checked == true) {
totalPrice = choiceRoyal.value;
}else {
totalPrice = 0;
}
if(tenTip.checked == true) {
var tipPrice = tenTip.value * totalPriceNum
} else if(fiveTip.checked == true) {
tipPrice = fiveTip.value
} else if(twentyTip.checked == true) {
tipPrice = twentyTip.value
} else {
tipPrice = 0
}
totalPriceNum = Number(totalPrice);
tipPriceNum = Number(tipPrice);
document.getElementById('total-amount').innerHTML = '$'+totalPriceNum;
答案 0 :(得分:1)
在不了解全部范围的情况下,我认为在您的情况下,totalPriceNum = Number(totalPrice) + Number(tipPrice);
将是总计。
如果已经声明了totalPrice
和tipPrice
的值,则可能要使其成为JS
中的函数
作为函数,例如:
function refreshTotal(){
var totalNumBeforeTip = Number(totalPrice);
if(tenTip.checked == true) {
var tipPrice = tenTip.value * totalPriceNum
} else if(fiveTip.checked == true) {
var tipPrice = fiveTip.value
} else if(twentyTip.checked == true) {
var tipPrice = twentyTip.value
} else {
var tipPrice = 0;
}
var tipPriceNum = Number(tipPrice);
var combinedTotal = totalNumBeforeTip + tipPrice;
var priceResultElement = document.getElementById('total-amount');
priceResultElement.innerHTML = '$'+combinedTotal;
}
在html中类似:
add $5 tip <input type="checkbox" id="tip-5" value="5.00" onChange="refreshTotal()">
答案 1 :(得分:0)
尝试一下
HTML
<input id="tenTip" class="tipSelector" name="tip" data-tip-value="10" type="radio" />
<input id="fiveTip" class="tipSelector" name="tip" data-tip-value="5" type="radio" />
<input id="twentyTip" class="tipSelector" name="tip" data-tip-value="20" type="radio" />
JS
const totalAmount = document.getElementById('total-amount');
document.querySelectorAll('.tipSelector').forEach(tipSelector => {
tipSelector.onclick = () => {
totalAmount.innerHTML = totalPriceNum * (1 + tipSelector.dataset.tipValue / 100);
}
})