如何使用localstorage保持变量的值?

时间:2016-02-03 00:49:02

标签: jquery jquery-ui local-storage

例如,我在这里可以拖动,一旦if语句为true,它将在wins变量中存储1。但是在刷新页面或转到另一个页面后,它仍将保留该值,因为我计划再次调用该变量。如何在本地存储中保留变量值?

2 个答案:

答案 0 :(得分:1)

将变量设置为本地存储:

//you store with a key ie. "winner" and then the value (your variable)
localStorage.setItem("winner", winner)

//then to get the value
winner = localStorage.getItem("winner")

答案 1 :(得分:0)

你可以这样做:

var winner = localStorage.getItem('winner');
if (!winner && winner !== 0) {
    localStorage.setItem('winner', 0);
}
$("#car").draggable({
    revert: "invalid", containment: "#wrapper",
    start: function(event, ui){
        if(!done) return false;
    },
    stop: function(event, ui){
        if($(".correct").length == $(".drop").length){
            setTimeout(function(){
                 $('#win').text(winner+' '+'stars'+' '+'earned');
            },500);
            winner = localStorage.getItem('winner');
            winner++;
            localStorage.setItem('winner', winner);

            clearInterval(timer);
        }
    } 
});

如果您建立了本地存储项目"胜利者"并确保它被初始化为一个整数,你可以递增它并使用该项来保持整个页面请求。