在本地存储中设置对象的值

时间:2019-01-16 15:21:29

标签: javascript local-storage

我想将用户数据作为单个对象存储在本地存储中。

下面是代码,下面是问题描述:

const firstName = document.getElementById('firstname');
const lastName = document.getElementById('lastname');
const address = document.getElementById('address');
const city = document.getElementById('city');
const postCode = document.getElementById('postcode');
const email = document.getElementById('email');
const checkBox = document.getElementById('check-remember');
const message = document.getElementById('message');

// define userData object 

let userData = {
    firstName: '',
    lastName: '',
    address: '',
    city: '',
    postCode: '',
    email: '',
    checkBox: '',
    message: ''
};

// set this object as string in the LS 

localStorage.setItem('userData', JSON.stringify(userData));

// parse it to native JS data and store it in new var

let userDataNative = JSON.parse(localStorage.getItem('userData'));

// add event listeners to form's input fields: 

firstName.addEventListener('keyup', setFirstName);
lastName.addEventListener('keyup', setLastName);
address.addEventListener('keyup', setAddress);
city.addEventListener('keyup', setCity);
postCode.addEventListener('keyup', setPostCode);
email.addEventListener('keyup', setEmail);
message.addEventListener('keyup', setUserMessage);

// set actual input values as userData object's value for each key

function setFirstName(event) {
    userData.firstName = event.target.value;
}
function setLastName(event) {
    userData.lastName = event.target.value;
}
function setAddress(event) {
    userData.address = event.target.value;
}
function setCity(event){
    userData.city = event.target.value;
}
function setPostCode(event){
    userData.postCode = event.target.value;    
}
function setEmail(event){
    userData.email = event.target.value;
}
function setUserMessage(event){
    userData.message = event.target.value;
}

问题:本地存储中的userData对象未更新。当我在页面上的输入字段中输入一些文本,然后登录userData时,确实在控制台中获得了带有右键和实际值的对象-但是Local Storage中的userData对象保持为空。

可以帮忙吗?我在这里想念什么?

非常感谢,所有帮助都很感激。

1 个答案:

答案 0 :(得分:0)

似乎您假设userData是对localStorage的引用,但事实并非如此。由于localStorage是一个字符串,您必须将其解析为javascript对象,因此没有这种关系。这意味着,要将信息重新保存到localStorage,您需要再次执行以下代码。

localStorage.setItem('userData', JSON.stringify(userData));