【问题标题】:JSON Local Storage not saving after the page refresh页面刷新后 JSON 本地存储未保存
【发布时间】:2019-09-06 03:07:05
【问题描述】:

这里是新手。我正在开发一个具有数组的项目,并允许用户通过在文本框中键入新项目然后单击“提交”按钮来将新项目添加到数组中。我这样做是为了让数组在我卸载页面时转换为 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>

你能告诉我吗?

【问题讨论】:

  • 你在哪里设置 'Items' 比如 set localStorage.setItem('Items', VALUE)???
  • onloadonunload中使用不指向方法的变量非常混乱

标签: javascript jquery json local-storage


【解决方案1】:

是的,我们有几个代码问题。这个剪断效果很好。

<!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>

【讨论】:

    【解决方案2】:

    我怀疑问题出在 2 个不同的键上。您使用 TemasEFrases 作为设置项目的键,但在检索时使用 Items 作为键。尝试在两个地方都使用Items

    假设您使用 jQuery 进行 DOM 操作,我在 JS Bin 上创建了一个有效的 sn-p。

    HTML

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    <body>
      <body>
    
        <textarea id="type" rows="2" cols="25"></textarea>
    
        <button id="submit" type="button">Submit</button>
    
        <p>Items:</p>
    <script src="https://code.jquery.com/jquery-3.0.0.js"></script>
        <ul id="result"></ul>
    </body>
    </html>
    

    JS

    $(document).ready(function () {
      var localstorageItems = JSON.parse(localStorage.getItem('Items'));
      var items = localstorageItems || [];
    
      showItems();
    
    
      $('#submit').click(function(event) {
        event.preventDefault();
    
        var newitem = $("#type").val()
    
        if (newitem) {
          items.push(newitem);
          $('#type').val('');
    
          localStorage.setItem('Items', JSON.stringify(items));
          showItems();
        }
      });
    
      function showItems () {
        if (items && items.length > 0) {
          var result = items.map(function (item) {
            return '<li>'+item+'</li>';
          });
    
          $('#result').html(result);
        }
      };
    });
    

    这里是工作代码https://jsbin.com/yoqoyoxiza/edit?html,js,output的链接

    【讨论】:

    • 哦,对不起,原来是 TemasEFrases,但我把所有东西都改成了英文,以便在这里更容易理解。感谢您发现我的错误:)
    【解决方案3】:

    您需要在每次更改后将其保存到本地存储:

     $("#submit").click(function() {
            var newitem = $("#type").val();
            if (newitem) {
                Items.push(newitem);
                $("#type").val("");
                // HERE:
                localStorage.setItem("Items", JSON.stringify(Items));
            }
     })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-12
      • 1970-01-01
      • 2011-10-14
      • 2017-08-13
      • 2021-05-31
      • 1970-01-01
      • 2021-08-09
      • 2020-12-30
      相关资源
      最近更新 更多