我想做的是获取用户的电子邮件和名称输入,并将其.push到数组emailbook中,它确实将电子邮件和名称的.values推送到数组中,但是每当我将其存储到本地存储中时,它替换了现有的数组。帮助请谢谢!!
<script>
document.addEventListener("DOMContentLoaded",docIsReady);
var emailbook;
function docIsReady(){
emailbook=localStorage.getItem("emailbook");
if (emailbook==null){
emailbook=[];
console.log(emailbook)
}
else {
emailbook=JSON.parse(emailbook);
console.log(emailbook)
}
}
function store() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var obj = {"name": name, "email": email};
emailbook.push(obj);
localStorage.setItem("email", JSON.stringify(emailbook));
}
console.log(localStorage);
//var storedemail = JSON.parse(localStorage.getItem("email"));
</script>
答案 0 :(得分:1)
如何在store()方法中读取localStorage,将所有内容推送到电子邮件簿数组,推送obj并将其保存在localStorage中呢?
类似这样的东西:
var name = "foobar";
var email = "mail";
var emailbook = [];
var obj = {"name": name, "email": email};
if(localStorage.getItem('email') != null) {
var tmp = JSON.parse(localStorage.getItem('email'));
for(let i = 0;i<tmp.length;i++) {
emailbook.push(tmp[i]);
}
}
emailbook.push(obj);
localStorage.setItem("email", JSON.stringify(emailbook));