带有cookie的javascript计数器不起作用

时间:2017-05-18 11:32:04

标签: javascript cookies setcookie

我只是尝试制作一个带有cookie的计时器,这使得按钮只能点击3次(我必须使用cookie,因为它会在其过程中刷新页面),我制作了这个计时器,但它没有工作。我的页面上没有任何内容发生变化。

//something else happens的代码由程序执行。

计时器 - (或者至少我认为可以用作计时器):

mailagain.onclick = function () {
    if (typeof getCookie("countIt") !== 'undefined') {
        if (checkCookie("countIt") > 3) {
            // something happens
        } else {
            //something else happens
            var counter = checkCookie("countIt") + 1;
            setCookie("countIt", counter, 1)
        }
    } else {
        setCookie("countIt", 1, 1)
    }
};

Coockie功能:

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 + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.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(name) {
    var value = getCookie("name");
    if (value != "") {
        return value;
    }
}

2 个答案:

答案 0 :(得分:2)

一些问题:

  • 从cookie中读取值时,请注意它具有字符串数据类型。您需要将其转换为数字,然后再将其与另一个数字进行比较或将其加1。
  • 函数checkCookie使用错误的(硬编码)cookie名称,但甚至不需要作为函数。您可以使用getCookie完成所有操作。

这是一个工作版本:

mailagain.onclick = function () {
    // make sure to convert to number (unitary plus), or use 0 when it is not a number:
    var counter = (+getCookie("countIt") || 0) + 1;
    setCookie("countIt", counter, 1)
    if (counter > 3) {
        console.log('clicked too many times! (', counter, ')');
    } else {
        console.log('clicked ' + counter + ' number of times.');
    }
};

答案 1 :(得分:0)

var value = getCookie("name"); 
由于错误的cookie名称,

getCookie始终返回“undefined”。移除支架。

function checkCookie(name) {
    var value = getCookie(name); //here you go
    if (value != "") {
        return value;
    }
}
相关问题