【问题标题】:How to add values as a list in localStorage?如何在 localStorage 中将值添加为列表?
【发布时间】:2018-03-27 10:53:16
【问题描述】:

我使用以下内容向本地存储添加值:

var thisId = "<?php echo $id; ?>";
localStorage.setItem("postId", thisId);
console.log(localStorage.getItem("postId"));

每次都会为我最终进入的每个页面加载以下内容

<?php echo $id; ?>

所以它会变成:242248

事情是每次我做console.log(localStorage.getItem("postId")); 我只得到一个值,因为它不是作为值列表添加而是用新值替换旧值。

【问题讨论】:

    标签: javascript jquery local-storage


    【解决方案1】:

    改为使用列表。由于您只能将 Strings 存储到 localStorage,因此最好的方法是使用 JSON parse/stringify 方法来帮助您进行数据序列化。

    • 以列表形式获取本地存储项 (JSON.parse)
    • 添加项目
    • 将列表保存到本地存储(JSON.stringify)

    var thisId = "1";//<?php echo $id; ?>
    
    var localList = localStorage.getItem("postIdList") || "[]";
    localList = JSON.parse(localList);
    
    //Check repeated ID
    var isExistingId = localList.indexOf(thisId) > -1;
    if (!isExistingId) {
      localList.push(thisId);
    }
    
    localStorage.setItem("postIdList", JSON.stringify(localList));
    console.log(localStorage.getItem("postIdList"));

    【讨论】:

    • 可以提供代码示例而不是概念逻辑吗?为未来的用户说这个也结束了这里
    • 非常感谢代码,当我运行 sn-p 时它有点坏了,但我明白了,谢谢
    【解决方案2】:

    请务必等待所有文档组件加载完毕,然后您可以将 PHP 值直接插入 lcoalStorage。不过要小心,localStorage 只能包含简单的变量,不能包含对象或数组。如果要存储对象或数组,请务必在保存前stringify

    document.addEventListener('DOMContentLoaded', function(event){
        localStorage.setItem("postIdList", JSON.stringify ("<?=$idList?>") );
        console.log( JSON.parse ( localStorage.getItem("postIdList") ) );
    });
    

    编辑。 这是一个如何将 PHP 数组转换为 JSON 并从那里将其存储在 localStorage 中并将其转换回 JSON 的示例。

    <?php
    $listIds = [1,2,5];
    $jsonIds = json_encode( $listIds );
    ?>
    <script>
        localStorage.setItem( "myIds", "<?=$jsonIds?>" );
        console.log( JSON.parse( localStorage.getItem( "myIds" ) ) );
    </script>
    

    【讨论】:

    • @RoryMcCrossan 完全正确
    • @RoryMcCrossan 除了我实际上解释说 OP 不能在 localStorage 中存储对象/数组。
    • 那么,如果您向 OP 展示执行此操作的代码,将会有所帮助,因为您当前的示例只是在回应他们的问题。
    • @RoryMcCrossan 已编辑。还编辑了变量,因为它们暗示了单个值,而不是数组或对象。
    • @rob.m 我已经更新了我的答案。查看第二部分,了解如何将 PHP 数组转换为 JSON 并返回到 Javascript 数组的示例。
    【解决方案3】:

    下面是一个非常简单的示例,可以将随机数添加到列表中,您可以根据需要进行更改..

    //first get current lines
    var lines = localStorage.getItem("lines") ?
      JSON.parse(localStorage.getItem("lines")) : []; 
    
    //lets add a random number to the list
    lines.push(Math.random()); 
    console.log(lines); 
    
    //now lets save our new list
    localStorage.setItem("lines", JSON.stringify(lines));
    

    【讨论】:

    • 嗯,发生的事情是每次我加载它都会创建一个新数组
    • 这是最后使用你的答案var thisId = "&lt;?php echo $id; ?&gt;"; var lines = localStorage.getItem("lines") ? JSON.parse(localStorage.getItem("lines")) : []; var myIdString = JSON.parse(localStorage.getItem("lines")); lines.push(thisId); function unique(list) { var result = []; $.each(list, function(i, e) { if ($.inArray(e, result) == -1) result.push(e); }); return result; } console.log(unique(lines));
    • 不确定我是否应该接受你的答案,也许我会添加到我的答案中,因为你的答案不完整,因为我在加载页面时确实在列表中说了一个新的 id
    【解决方案4】:

    Working Fiddle

    localStorage 所以只支持字符串。

    var id = [];// For sample
    id[0] ="1";
    id[1] ="2";
    localStorage.setItem("ids", JSON.stringify(id));
    var storedIds = JSON.parse(localStorage.getItem("ids"));
    console.log(storedIds);
    

    【讨论】:

    • 这很好,所以基本上var thisId = "&lt;?php echo $id; ?&gt;"; var id = []; id.push(thisId);
    • Yap 编码快乐 :)
    • 嗯,发生的事情是每次我加载它都会创建一个新数组
    • 根据这个旧答案stackoverflow.com/questions/2989284/… 本地存储有一些限制,所以尝试重用数组而不是每次都创建新数组或删除旧数组并创建新数组。
    【解决方案5】:

    可能不是最漂亮的,如果需要两个以上,它会变得很长,但这是一个解决方案。

    所以基本上我创建了两个 localStorage,我首先检查它们是否为空,以及键是否与我设置的变量不同,并且每次加载页面时都执行此操作。

    if(!localStorage.getItem("idA")) {
      var thisId = "<?php echo $id; ?>";
      localStorage.setItem("idA", thisId);
      console.log("A " + localStorage.getItem("idA"));
    } else {
      console.log("A " + localStorage.getItem("idA"));  
    }
    if(localStorage.getItem("idA") != "<?php echo $id; ?>") {
      if(!localStorage.getItem("idB")) {
        var thisId = "<?php echo $id; ?>";
        localStorage.setItem("idB", thisId);
        console.log("B " + localStorage.getItem("idB"));
      } else {
        console.log("A " + localStorage.getItem("idA"));  
        console.log("B " + localStorage.getItem("idB"));
      }
    }
    

    更新

    根据 Keith Answer,添加唯一值 (see this reply on SO),这就是我所做的:

    var thisId = "<?php echo $id; ?>"; 
    var lines = localStorage.getItem("lines") ? JSON.parse(localStorage.getItem("lines")) : []; 
    var myIdString = JSON.parse(localStorage.getItem("lines")); 
    lines.push(thisId); 
    function unique(list) { var result = []; 
    $.each(list, function(i, e) { 
      if ($.inArray(e, result) == -1) result.push(e); }); 
      return result; 
    } 
    console.log(unique(lines));
    

    【讨论】:

    • 与其他人提到的仅使用 1 localeStorage 插槽和 JSON.stringify / parse 相比,这有什么更好的方法?.. 这种方法似乎非常不灵活,与1 个 localeStorage 项目..
    • 它确实不灵活,也不是绝对最好的解决方案。发生的情况是var thisId = "&lt;?php echo $id; ?&gt;"; 是在每次页面加载时设置的新 ID,我理解 jSon 字符串技巧,但是,每次加载页面时,都会添加值,因此其他答案将替换每个页面加载时的值,而不是添加它
    • @Keith 看到你的JSON.parse(localStorage.getItem("lines")) : []; 是在我们每次页面加载时创建的
    • 如果不存在则创建,否则从localStorage加载。如果您在 Chromes 控制台中运行我的代码,每次运行时都会将一个随机数添加到列表中,.. 刷新浏览器,如果它被关闭,列表将继续等等。这不是您想要的吗?
    • 让我试一试,可能有用,但还没有真正尝试过你的。我也在考虑使用contains 并添加新的string(感谢JSON.stringify / parse 技巧)如果不存在
    【解决方案6】:

    setItem 替换与该特定键对应的字符串(如果存在)。 正如另一个答案中所建议的那样,获取当前的值数组更新它并对其进行字符串化。

    确保将代码包装在 try catch 中,因为 json.parse 可能引发异常

    try{
       let currentArray = Array.isArray(JSON.parse(localStorage.getItem("postId"))) 
         ? JSON.parse(localStorage.getItem("postId")) 
         : [];
       currentArray.push(thisId);
       localStorage.setItem("postId", JSON.stringify(currentArray));
    }
    catch(err){
       localStorage.setItem("postId", "[]");
    }
    

    https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多