gpt4 book ai didi

JavaScript - JSON - 本地存储

转载 作者:行者123 更新时间:2023-11-28 13:19:43 24 4
gpt4 key购买 nike

谁能告诉我为什么在尝试运行这段代码时我的页面上没有任何输出?

我正在尝试解析 localStorage 元素并使用 for 循环为每个元素创建一个表。然后我添加总价。

注意:localStorage 包含 3 个元素并且不是是空的。

<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<style>img{ height: 100px; float: left; }</style>
<link rel="stylesheet" type="text/css" href="style.css">

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>


<script>

function ShoppingCart() {

var totalPrice = 0;
var output;

for (var i = 0; i < localStorage.length; i++){

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);
productSubTotal = productQuantity * productPrice;

totalPrice = totalPrice + productSubTotal;


outputName = "<div id='cart-table'><table><tr><td>NAME:" + productName + "</td></tr></div>" ;
outputAlbum = "<tr><td>ALBUM:" + productAlbum + "</td></tr>" ;
outputQuantity = "<tr><td>QUANTITY:" + productQuantity + "</td></tr>";
outputPrice = "<tr><td>PRICE:" + productPrice + "</td></tr>";
outputSubTotal = "<tr><td>SUB-TOTAL" + productSubTotal + "</td></tr></table><br><br>";




}

var outputTotal = "<table><tr><td>" + totalPrice + "</td></tr></table>";
var TotalOutput = outputName + outputAlbum + outputQuantity + outputPrice + outputSubTotal + outputTotal;
document.getElementById("Cart-Contents").innerHTML=TotalOutput

alert(TotalOutput);
}

window.onload = ShoppingCart();


</script>


</head>
<body>
<div id="wrapper">

<header id="header">
<strong><table id="menu"><tr><td>Home</td><td>Contact</td><td>Login</td><td></td><td>Products</td></tr></table></strong>
</header>
<section id="middle">

<div id="container">
<div id="content">
<a class="" onclick="ShoppingCart()"><span>Cart</span></a>
<div id="Cart-Contents">


</div>


</div><!-- #content-->
</div><!-- #container-->

<aside id="sideLeft">
<strong>Left Sidebar:</strong>
</aside><!-- #sideLeft -->

<aside id="sideRight">
<strong>Right Sidebar:</strong>
</aside><!-- #sideRight -->

</section><!-- #middle-->

</div><!-- #wrapper -->



<footer id="footer">
<strong>by Brian Livori</strong>
</footer><!-- #footer -->
</body>
</html>

最佳答案

很简单,改一下

window.onload = ShoppingCart();

window.onload = ShoppingCart;

window.onload 是一个回调函数引用。当您分配 ShoppingCart() - 您实际上是将函数执行的结果分配给 window.onload

此处示例 http://jsbin.com/urikub/1/edit

关于JavaScript - JSON - 本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16204620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com