使用localStorage存储数值

时间:2017-03-31 02:22:14

标签: javascript html5

我正在尝试使用localStorage来保持基于HTML5的游戏中玩家健康的价值,当HP值低于0时,没有任何反应。

<!--Calling Statement-->
<ul>
    <li><a href="../S5/S5.html" onclick="alterHP(-3);"
        class="ghost-button">Go on to the next scene</a></li>
</ul>

在单独的.js文件中

function declareHP() {
    if (typeof (Storage) !== "undefined") {
        localStorage.setItem("HP", "20");
    } else {
        /*Can't Store, Oh well*/
    }
}

function alterHP(value) {
    if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.HP);
        localStorage.HP = currentHP + value;
        if (!(parseInt(localStorage.HP) > 0)) {
            window.location.assign('../youLose.html');          
        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果更改了行

$( "table tr td:first-child" )
  .css( "text-decoration", "underline" )
  .hover(function() {
    $( this ).addClass( "gogreen" );
  }, function() {
    $( this ).removeClass( "gogreen" );
  });

var theFirstChilds = document.querySelectorAll('table tr td:first-child');

console.log(theFirstChilds[0]);
console.log(theFirstChilds[1]);
console.log(theFirstChilds[2]);

ksort()

它会起作用

你可以这样做

var currentHP = parseInt(localStorage.HP);

答案 1 :(得分:0)

function setterfunc(targetedelement, presetting) {
    if(localStorage.getItem(targetedelement) == undefined) {
        localStorage.setItem(targetedelement, presetting);
    }
}
setterfunc('HP', 0);

现在,您可以根据您尚未初始化值localStorage.HP的注释运行您的脚本,以便初次使用。现在您可以运行脚本。

/*Function*/
function alterHP(value) {
if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.getItem("HP"));
        localStorage.setItem("HP", currentHP + value);
        if (!(parseInt(localStorage.getItem("HP") > 0)) {
            window.location.assign('../youLose.html');          
        }
    }
}