[英]Adding the total cost of a shopping cart
Hi I am trying to add up the total price each time a new item is added to the cart. 嗨我想在每次将新商品添加到购物车时将总价格加起来。 I know the code can be written cleaner and more complex but I have been asked to use this format. 我知道代码可以编写得更清晰,更复杂,但我被要求使用这种格式。 With my current code the total stays at 0. My buttons are working fine. 使用我当前的代码,总数保持为0.我的按钮工作正常。
var price = 0;
var totalPrice = 0;
var cartSummary = "";
price = product1.price;
cartSummary += product1.name + " €" + product1.price + "<br>";
totalPrice += product1.price;
document.getElementById("cart").innerHTML = cartSummary;
Make the function return the value you want to add and outside the function add the value: 使函数返回要添加的值,并在函数外添加值:
function addValue(product1) {
price = product1.price;
cartSummary += product1.name + " €" + product1.price + "<br>";
document.getElementById("cart").innerHTML = cartSummary;
return product1.price;
}
totalPrice += addValue(product1);
You need to make the following changes to your code: 您需要对代码进行以下更改:
cartSummary += product1.name + " €" + product1.price + "<br>"; becomes `cartSummary = product1.name + " €" + product1.price + "<br>";`
And totalPrice += product1.price;
而totalPrice += product1.price;
becomes totalPrice += number(product1.price);
成为totalPrice += number(product1.price);
document.getElementById("cost").innerHTML = totalPrice;
我忘了在函数中添加这一行,所以它没有在HTML中更新感谢您的帮助,无论如何
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.