1
編輯:由於我的問題似乎不清楚,我將重述我的問題。如何正確使用本地存儲?
我需要:在本地存儲
存儲變量。我有一個按鈕可以做到這一點。
檢索變量的值,但只有當本地存儲中有任何值時。如果沒有,那麼我想設置標準值。
刪除本地存儲。我也有一個按鈕。
我在這種情況下使用下面的代碼,但變量scrapMetal
總是返回爲true。
的Javascript:
//Been to variables
var beenToPrison = true;
//Item variables
var scrapMetal = false;
//Room variables
var currentRoom = 'prison';
//Mission variables
var currentMission = 'breakOut';
//Store
$("#media-icon1").click(function() {
if (Modernizr.localstorage) {
localStorage.setItem("curmission", currentMission);
localStorage.setItem("curroom", currentRoom);
localStorage.setItem("scrpmtl", scrapMetal);
localStorage.setItem("beenprison", beenToPrison);
addText($('<p>Game saved.<br><br></p>'))
}
else {
addText($('<p>Browser does not support saving.<br><br></p>'))
}
console.log(scrapMetal);
});
//Remove storage
$("#media-icon2").click(function() {
if (Modernizr.localstorage) {
localStorage.removeItem('curroom', 'beenprison', 'scrpmtl', 'curmission');
addText($('<p>Save erased.<br><br></p>'))
}
else {
addText($('<p>Browser does not support saving so there is nothing to delete.<br><br></p>'))
}
console.log(scrapMetal);
});
//Add a P element to the placeholder in the focus screen
var addText = function(el) {
el.hide().appendTo('#placeholder').fadeIn(1000);
}
//Check if browser support local storage using a library
$(document).ready(function() {
if (Modernizr.localstorage) {
addText($('<p>Your browser supports local storage. Game data can be saved by pressing the save button.<br><br></p>'))
scrapMetal = localStorage.scrpmtl;
if (scrapMetal === null) {
scrapMetal = false;
}
else {
scrapMetal = localStorage.scrpmtl;
}
}
else {
addText($('<p>Your browser does not support local storage. Your game can not be saved. Please use another browser or update your current browser.<br><br></p>'))
}
console.log(scrapMetal);
});
檢查modernizer文檔...你確定'如果(Modernizr.localstorage)'不應該'如果(Modernizr.localStorage)'?注意案例的差異。或者只是使用'如果(window.localStorage)' – charlietfl
要在localStorage的設置鍵,你必須使用setItem爲localstorage.setitem(「鍵名,值),並得到它是localstorage.getItem(」鍵名「) – Geeky
@charlietfl'localstorage' – Bushido