我坚持用javascript计算价格。如果我喜欢按钮,它会打印价格,但点击两次后显示相同的价格。但它需要是例如:39 + 39 + 39 =价格。但它只显示39 ..
document.getElementById("btn").onclick = function()
{
price ();
}
function price()
{
var type = document.getElementById("tickettype").value;
var price;
switch(type)
{
case "normal":
price=39;
break;
case "vip":
price=99;
break;
}
var totaal = price;
printPrice(totaal);
}
function printPrice(p_totaal)
{
document.getElementById("totalprice").innerHTML = p_totaal;
}
答案 0 :(得分:2)
您必须在total
范围之外定义price()
变量,例如:
document.getElementById("btn").onclick = function()
{
price ();
}
var totaal = 0; // Changed here
function price()
{
var type = document.getElementById("tickettype").value;
var price;
switch(type)
{
case "normal":
price=39;
break;
case "vip":
price=99;
break;
}
totaal += price; // Changed here
printPrice(totaal);
}
function printPrice(p_totaal)
{
document.getElementById("totalprice").innerHTML = p_totaal;
}
您所做的是重新定义变量,而不是增加全局变量。
答案 1 :(得分:0)
将其存储在函数范围之外的变量中:
var currPrice = 0;
document.getElementById("btn").onclick = function()
{
price ();
}
function price()
{
var type = document.getElementById("tickettype").value;
var price;
switch(type)
{
case "normal":
price=39;
break;
case "vip":
price=99;
break;
}
currPrice = currPrice + price;
printPrice(currPrice);
}
function printPrice(p_totaal)
{
document.getElementById("totalprice").innerHTML = p_totaal;
}
答案 2 :(得分:0)
其他答案都是正确的。您还可以删除switch
语句,只使用故障单类型和价格之间的映射:
var total = 0;
var ticket_prices = {
'normal': 39,
'vip': 99
};
document.getElementById('btn').onclick = function() {
var type = document.getElementById('tickettype').value;
var price = ticket_prices[type];
total += price;
document.getElementById('totalprice').innerHTML = total;
}