这里是新手。我正在处理一个有数组的项目,它允许用户通过在文本框中键入新项然后单击“提交”按钮来将新项添加到数组中。我这样做是为了让数组在我卸载页面时转换为 JSON,并在我再次加载它时转换回 JavaScript。我的脚本用于将项目保存在本地存储中一段时间。经过一些代码重构后,程序突然停止在页面刷新时保存我的项目。我想对它进行编程,以便即使我关闭计算机它也会保存它。
我尝试在网上搜索我的问题的解决方案,但似乎没有人遇到类似问题。
我的代码:
<body onload="Items" onunload="JSONItems">
<textarea id="type" rows="2" cols="25"></textarea>
<button id="submit" type="button">Submit</button>
<script type="text/javascript">
var Items = JSON.parse(localStorage.getItem("Items"))
var JSONItems = localStorage.setItem("Items", JSON.stringify(Items))
if (!Items) Items= []
$("#submit").click(function() {
var newitem = $("#type").val()
if (newitem) {
Items.push(newitem)
$("#type").val("")
}
})
</script>
</body>
你能给我点建议吗?
最佳答案
是的,我们有几个代码问题。这个片段工作正常。
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body onload="LoadItems()" onunload="saveItems()">
<div>
<textarea id="inputBox" rows="2" cols="25"></textarea>
<button id="submit" type="button">Submit</button>
</div>
<div>
<p>Data in storage</p>
</div>
<div>
<textarea id="showData" rows="2" cols="25"></textarea>
</div>
<script type="text/javascript">
var Items = [];
function LoadItems() {
debugger;
Items = JSON.parse(localStorage.getItem("Items"));
if (!Items) Items = [];
$("#showData").val(JSON.stringify(Items));
}
function saveItems() {
var JSONItems = localStorage.setItem("Items", JSON.stringify(Items));
}
$("#submit").click(function() {
var newitem = $("#inputBox").val();
if (newitem) {
Items.push(newitem);
$("#inputBox").val("");
}
});
</script>
</body>
</html>
关于javascript - 页面刷新后 JSON 本地存储不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57810185/