如果頁面關掉再打開,以前所有的資料就不見了,這樣還能算一個夠格的記帳軟體嗎?不算!所以我們今天要來加上本地儲存的功能,讓使用者即使關掉頁面,再次打開也能看到以前的紀錄。
這是一個瀏覽器內建的儲存機制,可以在用戶端儲存資料,即使瀏覽器關閉也不會消失。Local Storage 在每個網站都是獨立的,彼此不能互相訪問。而 Local Storage 的存儲容量也有限制,每個域名下通常有 5MB。下面有幾個常用的函式:localStorage.setItem(key,value)
:儲存資料。localStorage.getItem(key)
:讀取資料。localStorage.removeItem(key)
:刪除資料。
在了解「什麼是 Local Storage」後,我們要實際應用在JavaScript裡。
在 addExpense()
增加:
//儲存到local storage
let expenses = JSON.parse(localStorage.getItem("expenses"))||[];
expenses.push({description,amount,note});
localStorage.setItem("expenses",JSON.stringify(expenses));
在 addIncome()
也增加一組類似的:
//儲存到 Local Storage
let incomes=JSON.parse(localStorage.getItem("incomes"))||[];
incomes.push({description,amount,note});
localStorage.setItem("incomes",JSON.stringify(incomes));
要注意自己的變數名稱是設置什麼!
function loadData(){
//加載支出記錄
let expenses=JSON.parse(localStorage.getItem("expenses"))||[];
expenses.forEach(Expense=>{
let expenseList = document.getElementById("expense-list");
let listItem = document.createElement("li");
listItem.innerHTML = `${expense.description}-$${expense.amount.toFixed(2)}<br>備註:${expense.note}`;
listItem.classList.add("expense-item");
expenseList.appendChild(listItem);
totalAmount += expense.amount;
});
document.getElementById("total-amount").innerText = totalAmount.toFixed(2);
let incomes = JSON.parse(localStorage.getItem("incomes"))||[];
incomes.forEach(income=>{
let incomeList = document.getElementById("income-list");
let listItem = document.createElement("li");
listItem.innerHTML = `${income.description}-$${income.amount.toFixed(2)}<br>備註:${income.note}`;
listItem.classList.add("income-item");
incomeList.appendChild(listItem);
totalIncome += income.amount;
})
document.getElementById("total-income").innerText = totalIncome.toFixed(2);
updateNetAmount();
}
window.onload = loadData;
另外,也要加入加載資料的函式,這樣才能在頁面加載時調用之前儲存的資料。
function loadData(){
totalAmount = 0;
totalIncome = 0;
//加載支出記錄
let expenses=JSON.parse(localStorage.getItem("expenses"))||[];
expenses.forEach(expense=>{
let expenseList = document.getElementById("expense-list");
let listItem = document.createElement("li");
listItem.innerHTML = `${expense.description}-$${parseFloat(expense.amount).toFixed(2)}<br>備註:${expense.note}`;
listItem.classList.add("expense-item");
expenseList.appendChild(listItem);
// 創建刪除按鈕
let deleteButton = document.createElement("button");
deleteButton.innerText = "刪除";
deleteButton.style.marginLeft = "10px";
// 設置刪除功能
deleteButton.addEventListener("click", function () {
expenseList.removeChild(listItem);
totalAmount -= expense.amount;
document.getElementById("total-amount").innerText = totalAmount.toFixed(2);
updateNetAmount();
// 更新 Local Storage,刪除對應的支出
expenses = expenses.filter(e => e !== expense);
localStorage.setItem("expenses", JSON.stringify(expenses));
});
listItem.appendChild(deleteButton); // 將刪除按鈕添加到項目中
expenseList.appendChild(listItem);
totalAmount += parseFloat(expense.amount);
});
document.getElementById("total-amount").innerText = totalAmount.toFixed(2);
let incomes = JSON.parse(localStorage.getItem("incomes"))||[];
incomes.forEach(income=>{
let incomeList = document.getElementById("income-list");
let listItem = document.createElement("li");
listItem.innerHTML = `${income.description}-$${parseFloat(income.amount).toFixed(2)}<br>備註:${income.note}`;
listItem.classList.add("income-item");
incomeList.appendChild(listItem);
// 創建刪除按鈕
let deleteButton = document.createElement("button");
deleteButton.innerText = "刪除";
deleteButton.style.marginLeft = "10px";
// 設置刪除功能
deleteButton.addEventListener("click", function () {
incomeList.removeChild(listItem);
totalIncome -= income.amount;
document.getElementById("total-income").innerText = totalIncome.toFixed(2);
updateNetAmount();
// 更新 Local Storage,刪除對應的收入
incomes = incomes.filter(i => i !== income);
localStorage.setItem("incomes", JSON.stringify(incomes));
});
listItem.appendChild(deleteButton); // 將刪除按鈕添加到項目中
incomeList.appendChild(listItem);
totalIncome += parseFloat(income.amount);
})
document.getElementById("total-income").innerText = totalIncome.toFixed(2);
updateNetAmount();
let storedBudget = parseFloat(localStorage.getItem("budget")) || 0;
if (storedBudget > 0) {
budget = storedBudget;
document.getElementById("current-budget").innerText = budget.toFixed(2);
}
}
window.onload = loadData;
除了支出、收入的紀錄需重載,預算、刪除鍵等也都應該加上。原本我忘記預算和刪除鍵也要一起重載,結果只留下了支出和收入的資料,卻無法刪除,也沒辦法查看之前的預算,加上代碼後,更出現了很多沒注意到的小問題,所以就透過 ChatGPT 來幫我除錯。其實大部分的函式都是之前用過的,大同小異,就是很多小細節,例如:變數名稱等,常常因為這些小細節造成功能無法正常運作。
還好最後有成功排除所有問題,成功實現本地儲存功能,上圖就是按重新載入,而下面的支出和收入紀錄以及上面的預算不會消失。然後我剛剛突然發現我的收入「記」錄打錯字,下次會更正😫😫