跨多个页面将项目添加到本地存储

时间:2015-12-09 15:57:02

标签: javascript local-storage

有两个文件。第一个:

<div class="someclass">text1</div>
<div class="someclass">text2</div>

<script>
  var foo = document.getElementsByClassName("someclass");
  var arr = Array.prototype.map.call(foo, function(elem) {
    return elem.innerHTML;
  });
  localStorage.foobar = JSON.stringify(arr);
  alert(localStorage.foobar);
</script>

这给出了:["text1","text2"]

第二个(文件相同,前两行中的内部文字除外):

<div class="someclass">text3</div>
<div class="someclass">text4</div>

<script>
  var foo = document.getElementsByClassName("someclass");
  var arr = Array.prototype.map.call(foo, function(elem) {
    return elem.innerHTML;
  });
  localStorage.foobar = JSON.stringify(arr);
  alert(localStorage.foobar);
</script>

这给出了:["text3","text4"]

我希望第二个文件提供["text1","text2","text3","text4"],或者["text3","text4","text1","text2"]

我该怎么做?

3 个答案:

答案 0 :(得分:3)

您需要检索以前存储的数据(如果有),并附加到该数组。类似的东西:

&#13;
&#13;
var foostr = localStorage.foobar || "[]";
arr = JSON.parse(foostr);

var foo = document.getElementsByClassName("someclass");

Array.prototype.forEach.call(foo, function(elem) {
  arr.push(elem.innerHTML);
});

localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

所以你需要查看是否有任何内容并将其连接到数组。

if (localStorage.foobar) {
    var prev = JSON.parse(localStorage.foobar);
    arr = arr.concat(prev);
}
localStorage.foobar = JSON.stringify(arr);

答案 2 :(得分:0)

您可以先使用JSON.parse()检索localStorage的内容后连接两个数组:

var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
    return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(JSON.parse(localStorage.foobar).concat(arr));
console.log(localStorage.foobar);