如何正确使用本地存储?

时间:2016-11-19 21:18:43

标签: javascript jquery modernizr

编辑:由于我的问题似乎不清楚,我会重新解释我的问题。

我需要:

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

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

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

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

1 个答案:

答案 0 :(得分:1)

只是想补充一点,数据应该在设置之前转换为JSON。

localStorage.setItem("scrapMetal", JSON.stringify(false));
JSON.parse(localStorage.getItem("scrapMetal"));

否则你会看到字符串&#34; false&#34;,而不是布尔值false。