我在localStorage的5個項目,然而,當我嘗試輸出的所有文件,一些localStorage的項目
只有2個項目被輸出,而不是全部。
JS是把成的localStorage:
$(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。這是怎麼回事?
爲了給你一個想法:
http://i.imgur.com/RmftSoU.png
http://i.imgur.com/qO8FQN8.png
你能爲此添加小提琴嗎? – DrColossos 2013-04-25 13:57:45
將'for'循環更改爲:'for(var i = 0; i
Ian
2013-04-25 13:58:15
爲什麼這兩條單獨的行在循環中初始化「產品」變量? – Pointy 2013-04-25 13:59:45