JavaScript cookie错误

时间:2015-08-25 02:54:08

标签: javascript html cookies

今天我正在努力学习如何使用Cookie,而且它还很顺利,直到我尝试制作一个Cookie,保存您在页面上的总秒数,包括以前的访问次数。它不是像1,2,3那样计数,而是计数为1,11,111,1111。这是我的代码:

<!DOCTYPE html>
<html>
<head>
<script>

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    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 "";
}

var value = getCookie('value');

window.setInterval(function(){

    value = value + 1;
    document.getElementById("value").innerHTML = value;
    setCookie("value", value, 365);

}, 1000);

</script>
</head>
<body>
<p>
<span id="value">0</span>
</body>
</html>

0 个答案:

没有答案