【问题标题】:How do I add Multiple Objects of a similar type to local storage如何将多个类似类型的对象添加到本地存储
【发布时间】:2019-07-04 02:51:05
【问题描述】:

我已经在这里和其他一些网站上看到了几种将对象添加到本地存储的解决方案,但我的问题略有不同。我想将几个相关项目保存到本地存储。 像这样的

<head>
<script type="text/javascript" src="jquery.js"></script>

</head>
<body>
<input type='text' id='firstname' placeholder="first name"><br>
<input type='text' id='surname' placeholder="surname"><br>
<button id='submit'>Add</button>

<div id='displaynames'>

 <script>
$(document).ready(function(){
    $('button').click(function(){

        firstname = $('#firstname').val();
        surname = $('#surname').val();
        $('#displaynames').append("<p>"+firstname+" "+surname+"</p>");

        var names = {
            id: //what goes here?,
            name: firstname,
            lastname: surname
        };

        localStorage.setItem('names:'+counter, JSON.stringify(names));
        counter++;
        $('#displaynames').html(localStorage.getItem('names'));

    });
})   
</script>
</body>

该对象的所有属性都将由用户提供,但没有两个对象具有相同的 id 来区分它们,更重要的是,没有两个对象可以具有相同的键名,这如何实现?我的代码中某处的某种循环?

我希望键像 names:1、names:2、names:3 等一样递增

【问题讨论】:

  • 您需要id 做什么?为什么不直接使用counter呢?

标签: javascript local-storage


【解决方案1】:

您也可以将counter 本身存储在 localStorage 中,因此每次需要添加新项目时,请确保增加计数器。

// Get current counter from LS and increment it
var counter = localStorage.getItem('counter');
counter++;

// Put names in LS with a new counter id
localStorage.setItem('names:'+counter, JSON.stringify(names));

// Put back the incremented counter into LS
localStorage.setItem('counter', counter);

但正如评论中所建议的那样,使用一个将所有names 放在其中的数组会更明智。添加新名称时,其id 可以简单地为"names:" + namesArray.length

【讨论】:

    【解决方案2】:

    尝试使用数组,可以将对象存储在数组中,我的例子:

    $(document).ready(function() {
      var allNames = [];
      $('button').click(function() {
        firstname = $('#firstname').val();
        surname = $('#surname').val();
        $('#displaynames').append("<p>" + firstname + " " + surname + "</p>");
    
        var names = {
          id: allNames.length,
          name: firstname,
          lastname: surname
        };
    
        allNames.push(names);
    
        localStorage.setItem('names', JSON.stringify(allNames));
        $('#displaynames').html(localStorage.getItem('names'));
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type='text' id='firstname' placeholder="first name">
    <br>
    <input type='text' id='surname' placeholder="surname">
    <br>
    <button id='submit'>Add</button>
    
    <div id='displaynames'></div>

    我希望 sn-p 有效。如果没有,我要做的是创建一个包含要存储的对象的数组:

    [
        {
           id: 0,
           name: "Foo",
           lastname: "Bar"
        },
    {
           id: 1,
           name: "Bar",
           lastname: "Foo"
        },
    {
           id: 2,
           name: "Bob",
           lastname: "Joe"
        },
    ]
    

    【讨论】:

      【解决方案3】:

      通过对其 ID 的串联引用来存储相似类型对象的代码:

          let productBag = window.localStorage.getItem("product_id");
      
          console.log(productBag);
      
          if (productBag != undefined) {
      
            let tempData = productBag + "," + product['_id'];
            window.localStorage.setItem("product_id", tempData);
      
          } else {
      
            window.localStorage.setItem("product_id", product['_id']);
      
          }
      

      通过 ID 显示项目的代码:

       var test =  window.localStorage.getItem("product_id")
      
       console.log(test.split(","));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多