0

我正在尝试获取和排序 localStorage 中的所有项目并将其输出到 HTML 页面。

这就是我正在做的事情:

  <script>

    function ShoppingCart() {

        var totalPrice = 0;
        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) // check if key startwith 'Product_'
            {
                var product =  localStorage.getItem('Product_'+i);

                var result = JSON.parse(product);

                var productName;
                var productAlbum;
                var productQuantity;
                var productPrice;
                var productSubTotal = 0;
                var totalPrice;

                productName = result.name
                productAlbum = result.album;
                productQuantity = result.quantity;
                productPrice = parseFloat(result.price).toFixed(2);
                productSubTotal = parseFloat(productQuantity * 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 outputTotal = "<table><tr><td><b>TOTAL:</b> EUR " + totalPrice + "</td></tr></table>";
                var TotalOutput = outputName + outputAlbum + outputQuantity + outputPrice + outputSubTotal + outputTotal;
                document.getElementById("Cart-Contents").innerHTML=TotalOutput;


            }
            }

            alert(TotalOutput);




    }

    window.onload = ShoppingCart;


</script>

唯一正在输出的项目是 localStorage 中名为“Proudct_0”的项目。其他不显示!

这就是我在 localStorage 中所拥有的:http: //i.imgur.com/sHxXLOL.png

知道为什么会这样吗?

4

1 回答 1

0

你的代码有问题。如果 Product_0 不在 localStorage 中,你怎么看?

var product =  localStorage.getItem('Product_'+i);
var result = JSON.parse(product);

可能为 null 并引发错误。

尝试这个:

for (var i = 0; i < localStorage.length-1; i++){
     var keyName = localStorage.key(i);
     if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
     {
        var product = localStorage.getItem(keyName);
        //do your code here
     }
}

更新

document.getElementById("Cart-Contents").innerHTML=TotalOutput;

它是替换,而不是附加

希望这有帮助!

于 2013-04-25T09:51:36.743 回答