我的代码中有一个错误,它只在重新加载时保存数组中的最后一个对象。我觉得我的addAccount()函数没有正确保存或插入数据。其他一切都正常。在我的控制台中,它显示数据正在插入到数组中,但是当我刷新时,我只保存最后一个对象。 我不知道该怎么做。
// The list of accounts array.
var accountsArray = [];
function addAccount() {
// Take fields and put user data into varables.
var accountName = document.getElementById('accountName').value;
var accountBalance = document.getElementById('accountBalance').value;
var accountType = document.getElementById("accountType");
var accountTypeSelected = accountType.options[accountType.selectedIndex].text;
var accountCurrency = document.getElementById("accountCurrency");
var accountCurrencySelected = accountCurrency.options[accountCurrency.selectedIndex].text;
var temporaryObject = {
'accountName': accountName,
'accountBalance': accountBalance,
'accountTypeSelected': accountTypeSelected,
'accountCurrencySelected': accountCurrencySelected
};
accountsArray.push(temporaryObject);
console.log(accountsArray);
saveAccountData();
showAccountsArray();
}
function saveAccountData() {
localStorage.setItem('accountsArray', JSON.stringify(accountsArray));
}
function showAccountsArray() {
//var accountsLocalStorage = JSON.parse(localStorage['accountsArray']);
if (localStorage.getItem("accountsArray") === null) {
document.getElementById("getStarted").style.visibility="visible";
document.getElementById("balanceToolbarName").style.visibility="hidden";
document.getElementById("accountsMainList").style.visibility="hidden";
} else {
var accountsLocalStorage = JSON.parse(localStorage['accountsArray']);
console.log(accountsLocalStorage);
var accountInfo = '';
var i = 0;
while (i < accountsLocalStorage.length) {
accountInfo += '<li class="swipeout"><a href="#" class="item-link"><div class="swipeout-content item-content"><div class="item-inner"><div class="item-title">' + accountsLocalStorage[i].accountName + '</div><div class="item-after">$' + accountsLocalStorage[i].accountBalance + '</div></div></div><div class="swipeout-actions-left"><a href="#" class="action1">Clear</a></div><div class="swipeout-actions-right"><a href="#" class="action1">Delete</a></div></a></li>';
document.getElementById("accountsList").innerHTML = accountInfo;
i++;
}
document.getElementById("getStarted").style.visibility="hidden";
document.getElementById("balanceToolbarName").style.visibility="visible";
document.getElementById("accountsMainList").style.visibility="visible";
}
}
&#13;
答案 0 :(得分:1)
根据您提供的链接测试,您的所有功能都能正常运行。页面加载后,它会成功从本地存储中检索数据(如果有)并显示在页面上。但是,全局数组变量accountsArray
将填充从本地存储中检索的数据。
您需要重新填充全局数组,否则当您调用saveAccountData
时,它将保存数组所包含的内容,这实际上会覆盖您在本地存储中的任何内容。要修复它,只需添加添加此代码块...
$(function(){
var data = localStorage.getItem("accountsArray");
if(data != null)
accountsArray = JSON.parse(localStorage.getItem("accountsArray"));
});