将数据保存到本地存储 [英] Save data to local storage
本文介绍了将数据保存到本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在本地存储中设置一组变量,但函数没有运行,我试图获得值,但没有运气,如何在本地存储中保存字段?
I'm trying to set a bush of variables in local storage but the function doesn't run, I've tried to get the value but without luck, How can I save fields in Local storage?
function setPerson(){
var person = { 'name': getElementById('name'), 'photo': getElementById('photo')};
// Put the object into the storage
alert(person);
localStorage.setItem('person', JSON.stringify(person));
};
HTML
在HTML中我来自字段放将值放入标签中并填充它们,但是当我尝试获取它们并保存它们时,没有任何事情发生...
HTML In the HTML I'm from fields put values into tags and they are populated, but when I try to fetch them and save them nothing is happening...
我还尝试在那里输出固定值,然后显示警报,但是它只显示对象而不是值
I also tried to out fixed values in there and then the alert is displayed, but then it only says object and not the value
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
alert('retrievedObject: ', JSON.parse(retrievedObject));;
推荐答案
您可以像这样使用localStorage:
You can use localStorage like this:
// Retrieve your data from locaStorage
var saveData = JSON.parse(localStorage.saveData || null) || {};
// Store your data.
function saveStuff(obj) {
saveData.obj = obj;
// saveData.foo = foo;
saveData.time = new Date().getTime();
localStorage.saveData = JSON.stringify(saveData);
}
// Do something with your data.
function loadStuff() {
return saveData.obj || "default";
}
jsFiddle
这篇关于将数据保存到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文