Javascript 选择tip时如何更新总金额
我正在创建一个简单的食品配送服务。我正在试图弄清楚,当选择“小费”时,如何更新总金额Javascript 选择tip时如何更新总金额,javascript,Javascript,我正在创建一个简单的食品配送服务。我正在试图弄清楚,当选择“小费”时,如何更新总金额 if(choiceRegular.checked == true) { var totalPrice = choiceRegular.value; }else if (choicePremium.checked == true) { totalPrice = choicePremium.value; }else if(choiceRoyal.checked
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;
在不了解全部范围的情况下,我认为在您的案例中,
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()">
添加$5小费
试试这个
HTML
只需使用复选框onclick event调用代码。Alex,欢迎使用堆栈溢出。请包括所有必要的HTML,以便有人复制您的应用程序。必须计算总价,并在单击时添加提示使其成为函数,例如函数refreshttotal(){//此处求和值并报告新的总计}
然后,您可以在调用该函数的HTML对象中为onChange
设置一个eventListener
,或一个onClick
。
<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" />
const totalAmount = document.getElementById('total-amount');
document.querySelectorAll('.tipSelector').forEach(tipSelector => {
tipSelector.onclick = () => {
totalAmount.innerHTML = totalPriceNum * (1 + tipSelector.dataset.tipValue / 100);
}
})