[英]Add items to local storage across multiple pages
There are two files. 有两个文件。 The first:
首先:
<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>
That gives: ["text1","text2"]
给出:
["text1","text2"]
The second (files are identical except inner text in first two lines): 第二个(除了前两行中的内部文本外,文件是相同的):
<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>
That gives: ["text3","text4"]
给出:
["text3","text4"]
I would like the second file to give ["text1","text2","text3","text4"]
, or maybe ["text3","text4","text1","text2"]
. 我希望第二个文件提供
["text1","text2","text3","text4"]
或["text3","text4","text1","text2"]
。
How can I do that? 我怎样才能做到这一点?
You need to retrieve the previously-stored data (if any), and append to that array. 您需要检索以前存储的数据(如果有),并将其追加到该数组。 Something like:
就像是:
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);
So you need to see if there is anything and concatenate it to the array. 因此,您需要查看是否有任何内容并将其连接到数组。
if (localStorage.foobar) {
var prev = JSON.parse(localStorage.foobar);
arr = arr.concat(prev);
}
localStorage.foobar = JSON.stringify(arr);
You can concat the both arrays after retrieving localStorage's contents first, using JSON.parse()
: 您可以先使用
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.