JavaScript - 即使刷新页面后也存储并增加数量

时间:2015-10-24 13:50:57

标签: javascript

此JavaScript代码应该增加数量



<script type="text/javascript">
var number = 100035;

function increment()
{
    number = Math.floor(Math.random() * 500) + number;
    showNumber(number);
}

function showNumber(num)
{
    document.getElementById("displayDiv").innerHTML = "€" + num;
}

window.onload = function()
{
    setInterval("increment()", 1000);
    showNumber(number);
}
</script>

<div id="displayDiv"></div>
&#13;
&#13;
&#13;

当用户刷新页面和用户返回网站时,我必须能够显示上次生成的数字。但是,该号码不会从上一个生成的号码继续,而是重新开始。

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:0)

我尽量避免使用间隔,所以我在这里使用setTimeout。

<script type="text/javascript">
var number = checkCookie();
var daysBeforeExpiration = 365;

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

function checkCookie() {
    var number = getCookie("number");
    if (number == "") {
        number = "100035"
        setCookie("number", number, daysBeforeExpiration);
    }
    return parseInt(number);
}

function showNumber(num)
{
    document.getElementById("displayDiv").innerHTML = "€" + num;
}

incrementInterval = function() {
    showNumber(number);
    number = Math.floor(Math.random() * 100) + number;
    setCookie("number", number.toString(), daysBeforeExpiration)

    setTimeout(incrementInterval, 1000);
};

window.onload = function () {
    incrementInterval();
};
</script>