如何设置,检索和删除本地存储?

时间:2016-11-20 13:08:57

标签: javascript jquery

我需要:

  • 将变量存储在本地存储上。我有一个按钮可以做到这一点。

  • 检索变量的值,但仅限于本地存储中有任何值。如果没有,那么我想设置标准值。

  • 删除本地存储空间。我也有一个按钮。

我在这种情况下使用以下代码,但变量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);
});

0 个答案:

没有答案