从其他页面加载localStorage

时间:2019-01-20 11:32:19

标签: javascript html json

所以我刚做了一个帐户,所以我希望我问对了,但是无论如何。我有两页。一个是菜单,第二个是HTML游戏。现在,菜单中有两个按钮。一个用于启动新游戏,第二个用于继续游戏。现在,第一个按钮将使您进入游戏,而第二个按钮将加载本地存储。现在的问题是变量无法覆盖。我尝试制作要保存在菜单中的变量,然后将其加载到第二页上,如果为0,则不会加载变量;如果为1,则不会加载变量,但这也不起作用,我真的不知道还有什么要做。

这是我的修改代码

<a href="javascript:void(0)" onclick="zacatek()">Play<br>
<a href="javascript:void(0)" onclick="pokracovanifn()">Continue</a>

function load() {
I got rid of the load feature as there was no button for it to use
}

function pokracovani() {
 pokracovani = 1;
 localStorage.setItem("pokracovani", JSON.stringify(pokracovani));
 location.href = "index.html";
}

function zacatek() {
 pokracovani = 0;
 try {
   pokracovani = JSON.parse(localStorage.getItem("pokracovani"));

 } catch (e) {

 }
 location.href = "index.html";
 }

对于游戏本身

document.onreadystatechange = function () {
if (document.readyState == "complete") {
    pokracovani = 2;
    pokracovani = JSON.parse(localStorage["pokracovani"]);
    if (pokracovani == 0) {

    }
    if (pokracovani == 1) {
            money = JSON.parse(localStorage.getItem("money"));
            wood = JSON.parse(localStorage.getItem("wood"));
            stone = JSON.parse(localStorage.getItem("stone"));
            food = JSON.parse(localStorage.getItem("food"));
    }
}
}

还有保存功能

function konec() {
 localStorage["money"] = JSON.stringify(money);
 localStorage["wood"] = JSON.stringify(wood);
 localStorage["stone"] = JSON.stringify(stone);
 localStorage["food"] = JSON.stringify(food);

1 个答案:

答案 0 :(得分:-1)

您可以尝试使用此代码

 <a href="javascript:void(0)" onclick="zacatek()">Play</a>
    <a href="javascript:void(0)" onclick="pokracovanifn()">Continue</a>

    <script>
        function load() {
            money = 0;
            try{
                JSON.parse(localStorage.getItem("money"));
            }catch(e){

            }
        }

        function pokracovanifn() {
            pokracovani = 1;
            localStorage.setItem("pokracovani", JSON.stringify(pokracovani));
             location.href = "/index.html";
        }

        function zacatek() {
            pokracovani = 0;
            try {
                pokracovani = JSON.parse(localStorage.getItem("pokracovani"));

            } catch (e) {

            }
           location.href = "/index.html";
        }


        document.onreadystatechange = function () {
            if (document.readyState == "complete") {
                pokracovani = 2;
                try {
                    pokracovani = JSON.parse(localStorage.getItem("pokracovani"));

                } catch (e) {

                }
                if (pokracovani == 0) {

                }
                if (pokracovani == 1) {
                    try {
                        money = JSON.parse(localStorage.getItem("money"));
                    } catch (e) {

                    }
                }
            }
        }

    </script>

enter image description here