如何在刷新时保存变量?

时间:2014-01-28 02:07:29

标签: javascript html variables save

<!DOCTYPE HTML>
<html>


<head>
    <title>Zautra Levels</title>
    <h2 style="font-family: Trebuchet MS; color: blue;"">Zautra Levels</h2>
    <p> </p>
</head>


<body>

<p>Clickables:</p>
<button id="swag" onclick="lmao()">Gain XP</button> <button id="gold" onclick="getgold()">Get Gold</button> <button id="buyupgrade" onclick="buyupp()">Level Up!</button>
<p> </p>
<div id="total">XP: 0</div>
<div id="goldt">Gold: 0</div>
<div id="upgradess">Level: 0</div>
<div id="upcostt">Required XP: 25</div>



<script>
    var clicks = 0; // How many clicks you have
    var upgrades = 0; // How many upgrades you have purchased
    var upcost = 25; // How much the upgrades cost
    var gold = 0; // How much gold you have

    function updateclicks() { // Declares the function that updates the "Zautra Clicks" Text.
        var v=document.getElementById("total");
        v.innerHTML = 'XP: ' + clicks;
    }

        function updategold() { // Declares the function that updates the "Zautra Clicks" Text.
        var g=document.getElementById("goldt");
        g.innerHTML = 'Gold: ' + gold;
    }

    function updateupgradecounter() { // Declares the function that updates the "Upgrades:" Text.
        var y=document.getElementById("upgradess");
        y.innerHTML = 'Level: ' + upgrades;
    }

    function updateupcost() { // Declares the function that updates the "Upgrade Cost:" Text.
        var z=document.getElementById("upcostt");
        z.innerHTML = 'Required XP:' + upcost;
    }

    var x=document.getElementById("swag"); function lmao() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
        clicks+=1;
        updateclicks();
    }

        var j=document.getElementById("gold"); function getgold() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
        gold+=1;
        updategold();
    }

    var c=document.getElementById("buyupgrade"); function buyupp() {
        if (clicks >= upcost) {
            clicks-=upcost
            upgrades+=1
            upcost*=2
            updateclicks();
            updateupgradecounter();
            updateupcost();
        }
        else
        {
            var clicksdif = upcost - clicks;
            confirm("You need " + clicksdif + " more XP to level up.");
        }
    }
</script>
</body>
</html>

这是我正在制作的游戏代码。 我正在尝试添加一个按钮,当您按下它时,它会保存所有变量。 如果您使用26 XP和7金牌获得5级,则刷新页面,您仍然可以获得这些统计数据,而不是在刷新时丢失它们。

请帮忙!

(是的,我确实意识到代码真的搞砸了,但这是一个小问题。我迟早会修复它。)

2 个答案:

答案 0 :(得分:0)

你可以在php中创建一个cookie:

setcookie("NameOfTheCookie",$value,$expireTime)

$value也可以是值数组。

答案 1 :(得分:0)

我认为实际上比Cookie更容易的方法是通过URL传递值。示例:

<form action="yourPage.php?gold=$amount&level=$whatlevel&experience=$experience" method="POST">

//这里的刷新按钮

</form> 

然后在页面重新加载时检索这些变量,使用:gold = $ _ POST [&#39; gold&#39;]

另一个选择是使用GET方法而不是POST。 请记住,文件扩展名需要为php才能使此代码生效。