Javascript 刷新后重置本地存储值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35659086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
localstorage values resetting after refresh
提问by igetstuckalot
i want to have an array (converted also to a localStorage value) box where the value of '#textInput' is added to the localStorage each time, however after refreshing and entering a new value, the new value is not added to the localStorage, but replaces it. I believe this is because after refreshing the data from users[] is set to null, but dont know how to fix it
我想要一个数组(也转换为 localStorage 值)框,其中 '#textInput' 的值每次都添加到 localStorage 中,但是在刷新并输入新值后,新值不会添加到 localStorage,但取代它。我相信这是因为从 users[] 刷新数据后设置为 null,但不知道如何修复它
var users = new Array();
var valueChanger = 1;
alert(localStorage.getItem('usernames'));
function addValue() {
var newUser = $('#textInput').val();
users.push(newUser);
localStorage.setItem('usernames', users);
alert(localStorage.getItem('usernames'));
}
回答by Rajaprabhu Aravindasamy
You have to rewrite your code like the below to make it working,
你必须像下面这样重写你的代码才能让它工作,
var users = JSON.parse(localStorage.getItem('usernames')) || [];
var valueChanger = 1;
alert(localStorage.getItem('usernames'));
function addValue() {
users.push($('#textInput').val());
localStorage.setItem('usernames', JSON.stringify(users));
alert(localStorage.getItem('usernames'));
}
Since localStorage
only stores string
, we need to stringify
the array before storing and Parse
it before reading.
由于localStorage
只存储string
,我们需要stringify
在存储之前和Parse
读取之前的数组。
回答by Amulya Kashyap
Everytime, when page refreshes you're first statement creates new array instead of using old one.
每次,当页面刷新时,您的第一个语句会创建新数组而不是使用旧数组。
var newUser = localStorage.getItem('usernames') || "";
var valueChanger = 1;
var users = [newUser];
alert(localStorage.getItem('usernames'));
function addValue() {
var newUser = $('#textInput').val();
users.push(newUser);
localStorage.setItem('usernames', users);
alert(localStorage.getItem('usernames'));
}
Thanks & Cheers :)
谢谢和干杯:)
回答by Observer
You are correct in that users is an empty array each time you refresh. Instead of using the new array "users" in your function. Grab the information (if any) out of localStorage.setItem('usernames', users); and set that to equal users. Then you can push additional users into usernames.
您是正确的,每次刷新时 users 都是一个空数组。而不是在您的函数中使用新数组“用户”。从 localStorage.setItem('usernames', users); 中获取信息(如果有的话);并将其设置为相等的用户。然后您可以将其他用户推送到用户名中。