来自javascript cookie的var被忽略

时间:2013-09-03 10:16:56

标签: javascript html cookies

我做了一个时间计数器。主题是从最后一页访问后停止的点开始。 例如,它是“00:02:21”并且在重新加载页面之后,它从这一点开始,而不是从一开始。 我决定使用cookies来达到这个目的。

想法从Cookie中获取 time var并使用它,然后在Cookie中重新 time

示例(http://jsfiddle.net/JuxZr/):

function simple_timer(sec, block) {
document.cookie = 'window.time=sec; expires=Thu, 2 Aug 2091 20:47:11 UTC; path=/; ;domain=.nekamera.ru'

var day = Math.floor(time / 86400);
time = (time - day * 86400);

var hour = Math.floor(time / 3600);

time = (time - hour * 3600);

if ( hour < 10 ) hour = '0'+hour;
var minutes = Math.floor(time / 60);
time = (time - minutes * 60);
if ( minutes < 10 ) minutes = '0'+minutes;
var seconds = time;
if ( seconds < 10 ) seconds = '0'+seconds;
block.innerHTML =  day + ' days ' +  hour+':'+minutes+':'+seconds;
sec--;
    if ( sec > 0 ) {
        setTimeout(function(){ simple_timer(sec, block); }, 1000);
    } else {
         simple_timer(15, block);}
       }

function start_countdown() {
    var block = document.getElementById('sample_countdown'); //restart the timer live
    simple_timer(15, block);
}


window.onload=start_countdown;

1 个答案:

答案 0 :(得分:0)

window.time=sec行:

document.cookie = 'window.time=sec; expires=Thu, 2 Aug 2091 20:47:11 UTC; path=/; ;domain=.nekamera.ru'

实际上从未被解析器解释,而只是存储为字符串。你想要做的是以字符串格式存储时间,然后在后续请求中将该字符串解析为变量。

设置Cookie:

document.cookie = 'time=' + sec + '; expires=Thu, 2 Aug 2091 20:47:11 UTC; path=/; ;domain=.nekamera.ru'

阅读Cookie:

// from w3schools
function getCookie(c_name)
{
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start == -1) {
        c_start = c_value.indexOf(c_name + "=");
    }
    if (c_start == -1) {
        c_value = null;
    } else {
        c_start = c_value.indexOf("=", c_start) + 1;
        var c_end = c_value.indexOf(";", c_start);
        if (c_end == -1) {
            c_end = c_value.length;
        }
        c_value = unescape(c_value.substring(c_start,c_end));
    }
    return c_value;
}

var time = parseInt(getCookie('time'));