1 回答

TA貢獻1802條經驗 獲得超6個贊
為了使用 localStorage 保存應用程序的狀態,您需要創建如下函數:
function save(slotIndex, clicks) {
let slots;
try {
slots = JSON.parse(localStorage.getItem('slots'));
} catch (e) {
console.error(e);
}
if (!slots) {
slots = [0, 0, 0, 0];
}
slots[slotIndex] = clicks;
localStorage.setItem('slots', JSON.stringify(slots));
}
function restore(slotIndex) {
let slots = [];
try {
slots = JSON.parse(localStorage.getItem('slots'));
} catch (e) {
alert('no slots found in local storage');
}
return slots[slotIndex] || 0;
}
這里有一個應用程序的版本,其中包含我的更改。
需要注意的是,我們保存的狀態只是已發生的點擊次數,這對應于將用于在一個國家著色的下一個顏色。
我懷疑你真正想要保存的是國家本身的顏色。
這將需要更復雜的數據結構:
const slots = [
{
currentColorIndex: 2,
selectedCountries: [
{ id: 'spain', colorIndex: 3 },
{ id: 'usa', colorIndex: 1 },
]
},
... other slots
];
只要將其字符串化(localStorage 中的所有值都必須是字符串),這也可以存儲在 localStorage 中。在您的應用程序中,每當您更改 SVG 中的顏色時,您都需要更新此結構,以確保它們彼此保持同步。
這是應用程序開始變得復雜的地方,我建議查看類似 MVC(模型視圖控制器)模式的內容,以了解開發人員通常如何處理此問題。
添加回答
舉報