存储后,Cookie表现得很奇怪

时间:2016-12-15 07:38:22

标签: javascript html cookies

我正在尝试将倒计时保存为Cookie。我想制作我上一次倒计时的饼干,每次重新加载它都应该从上次倒计时开始。但我的代码表现得如此奇怪。我无法弄清楚原因。这是代码段



window.onload = function() {
    var a = document.cookie.split("=");
    number = a[1];
}
var number = setInterval(thetimer,1000);


function thetimer() {
    
    document.getElementById("demo3").innerHTML = number;
    number += 1;
    return number;
}


function alertf() {
    var x;
    if (confirm("Press any key?") == true) {
        x = "you pressed ok";
    } else{
        x = "you pressed cancel";
    }
    document.getElementById("demo").innerHTML = x;
}

function getname() {
    var x;
    var name = prompt("Lets us know your name", "Chunnu Mia");
    if(name == "") {
        x = "What dont you telling??";
    } else {
        x = name+"!!! What a uselessname hahaha!!!";  
    }
    document.getElementById("demo2").innerHTML = x;
}
document.cookie = "countdown="+number+";expires=Fri, 15 oct 2022 01:00:00 UTC";

<html>
<head>
    <title>BOM</title>
    </head>
<body>
    
    <button onmouseover="alertf()">Dont touch me</button>
    <button onmouseover="getname()">Whats your name?</button>
    <p id="demo"></p>
    <script src="index.js"></script>
    <p id="demo2"></p>
    <p id="demo3"></p>
    <button onclick="clearInterval(timer)">Stop</button>
    <p>01795923372</p>
    </body>
</html>
&#13;
&#13;
&#13;

我应该在这里改变什么?

1 个答案:

答案 0 :(得分:0)

number是间隔的id,也是变量?

window.onload = function() {
    var a = document.cookie.split("=");
    number = Math.abs(a[1]);  ///Just in case))
}
var number = 0;
var timer = setInterval(thetimer,1000);


function thetimer() {

    document.getElementById("demo3").innerHTML = number;
    number += 1;
    ///return number; 

    document.cookie = "countdown="+number+";expires=Fri, 15 oct 2022 01:00:00 UTC";

}