我在localStorage中有5个项目,但是,当我尝试输出所有文件时,
仅输出2个项目,而不是全部。
放入localStorage的JS:
$(document).ready(function () {
$.fn.SaveToCart = function (id, iName, iAlbum, iPrice) {
var quantity = 0;
if (localStorage.getItem('Product_' + id) === null) {
quantity = 1;
} else {
var tempItem = JSON.parse(localStorage.getItem('Product_' + id));
var tempQuantity = parseInt(tempItem['quantity']);
quantity = tempQuantity + 1;
}
var cartItem = {
'quantity': quantity,
'name': iName,
'album': iAlbum,
'price': iPrice
}
localStorage.setItem('Product_' + id, JSON.stringify(cartItem));
};
购物车JS:
function ShoppingCart() {
var output;
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
for (var i = 0; i < localStorage.length - 1; i++) {
var keyName = localStorage.key(i);
if (keyName.indexOf('Product_') == 0) {
var product = localStorage.getItem(keyName);
var product = localStorage.getItem('Product_' + i);
var result = JSON.parse(product);
totalPrice = 0;
productName = result.name
productAlbum = result.album;
productQuantity = parseInt(result.quantity);
productPrice = parseFloat(result.price).toFixed(2);
productSubTotal = parseInt(productQuantity) * parseFloat(productPrice).toFixed(2);
outputName = "<div id='cart-table'><table><tr><td><b>NAME: </b>" + productName + "</td></tr></div>";
outputAlbum = "<tr><td><b>ALBUM: </b>" + productAlbum + "</td></tr>";
outputQuantity = "<tr><td><b>QUANTITY: </b>" + productQuantity + "</td></tr>";
outputPrice = "<tr><td><b>PRICE: </b> EUR " + productPrice + "</td></tr>";
outputSubTotal = "<tr><td><b>SUB-TOTAL: </b> EUR " + productSubTotal + "</td></tr></table><br><br>";
var TotalOutput = outputName + outputAlbum + outputQuantity + outputPrice + outputSubTotal;
document.getElementById("Cart-Contents").innerHTML = document.getElementById("Cart-Contents").innerHTML + TotalOutput;
totalPrice += parseFloat(totalPrice) + parseFloat(productSubTotal);
productSubTotal = productSubTotal + productSubTotal;
}
i++;
}
totalPrice = productSubTotal;
localStorage.setItem("price", totalPrice);
var outputTotal = "<br><br><h1><table><tr><td><b>TOTAL:</b> EUR " + totalPrice + "</td></tr></table></h1>";
document.getElementById("total-price").innerHTML = document.getElementById("total-price").innerHTML + outputTotal;
}
function ClearCart() {
localStorage.clear();
document.location.reload(true);
}
window.onload = ShoppingCart;
</script>
HTML:
<div id="Cart-Contents"></div>
<div id="total-price"></div>
另外,我还有另一个问题,总价格没有正确计算。我得到28.12,总计14.06 + 16.40。这是怎么回事?
给你一个想法:
答案 0 :(得分:1)
将您的for循环更改为:for (var i = 0; i < localStorage.length; i++){
。
不要将i++;
添加到循环体的末尾。
由于各种原因,两者都会导致你的循环没有击中所有项目。