2016-09-18 28 views
-3

如果在输入元素 中if语句中输入的数量为1,则我的下面的代码提示300400应该将700提醒为总数。js打印为文本,而不是计算


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

按所给的代码,输出将是'NaN' –

+0

烨如果我尝试VAR法案=“”;我得到300700,而不是700。等待让我更新问题 –

+0

如果你初始化'var bill =''',那么你会描述的结果会发生,因为你正在做字符串连接,使用'var bill = 0;'它应该可以工作。 – Barmar

回答

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); 
    }; 
}; 
相关问题