[英]Storing array in localstorage
I have a quiz page with multiple questions, the page shows 1 question at a time. 我有一个包含多个问题的测验页面,该页面一次显示一个问题。 The answers to the question are displayed in buttons.
问题的答案显示在按钮中。 Whenever a button is pressed the second question is grabbed from the database and is shown.
每当按下按钮时,第二个问题就会从数据库中获取并显示出来。 I have a script that puts the value of the pressed button in an array, but when the page is reloaded the array is emptied.
我有一个脚本,将按下按钮的值放入数组中,但是重新加载页面时,该数组将被清空。 I was told to use localstorage but I have no clue how this works, this is my code I use to store data in the array at the moment:
有人告诉我要使用localstorage,但是我不知道它是如何工作的,这是我现在用来在数组中存储数据的代码:
$( document ).ready(function() {
var antwoordenObject1= new Array();
$('.btn').click(function() {
antwoordenObject1.push($(this).val());
alert("newArray contents = "+ antwoordenObject1);
});
});
and I found this code to put an array into localstorage but don't know how to combine these two: 并且我发现此代码将数组放入本地存储,但不知道如何结合这两个:
var complexdata = [1,2,3,4,5,6];
// store array data to the localstorage
localStorage.setItem("list_data_key", JSON.stringify(complexdata));
//Use JSON to retrieve the stored data and convert it
var storedData = localStorage.getItem("complexdata");
if (storedData) {
complexdata = JSON.parse(storedData);
}
document.write(complexdata);
like this: 像这样:
$( document ).ready(function() {
var antwoordenObject1 = localStorage.getItem("antwoorden");
antwoordenObject1 = antwoordenObject1 ? JSON.parse(antwoordenObject1) : [];
$('.btn').click(function() {
antwoordenObject1.push($(this).val());
localStorage.setItem("antwoorden", JSON.stringify(antwoordenObject1));
alert("newArray contents = "+ antwoordenObject1);
});
});
You will have to use .setItem()
and .getItem()
methods of localStorage
. 你将不得不使用
.setItem()
和.getItem()
方法localStorage
。
Note: LocalStorage can only store strings. 注意: LocalStorage只能存储字符串。 So if you try:
因此,如果您尝试:
var a = {
test: "foo"
}
localStorage.setItem("test", a);
it will store [object Object]
and not object itself. 它会存储
[object Object]
而不是对象本身。 For arrays, it would be comma separated string. 对于数组,它将是逗号分隔的字符串。
You will have to use JSON.stringify
and JSON.parse
as well to communicate properly. 您还必须使用
JSON.stringify
和JSON.parse
才能正确通信。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.