如果输入元素的if语句中的数量为1 我的下面的代码警告300400它应该提醒700作为总和。
function validateCart() {
var check = false;
var bill="";
if (document.getElementById("bbc").checked) {
check = true;
var price = 300;
var quantity = document.getElementById("bbq").value;
var total = price * quantity;
bill += total;
};
if (document.getElementById("gbc").checked) {
check = true;
var price = 400;
var quantity = document.getElementById("gbq").value;
var total = price * quantity;
bill += total;
};
if (!check) {
alert("no item selected");
} else {
alert(bill);
};
};

我无法弄清楚我做了什么错误。
答案 0 :(得分:1)
您需要将帐单初始化为0:
function validateCart() {
var check = false;
var bill = 0;
if (document.getElementById("bbc").checked) {
check = true;
var price = 300;
var quantity = document.getElementById("bbq").value;
var total = price * quantity;
bill += total;
};
if (document.getElementById("gbc").checked) {
check = true;
var price = 400;
var quantity = document.getElementById("gbq").value;
var total = price * quantity;
bill += total;
};
if (!check) {
alert("no item selected");
} else {
alert(bill);
};
};