读取动态创建的cookie名称

时间:2017-01-03 15:27:30

标签: javascript jquery cookies cookiestore

我有一组用作提醒的热门消息。他们有 X 来关闭它们。关闭它们会设置一个cookie,使它们永远消失,cookie的名称取自您关闭的特定顶部消息的id

我有一个用于创建,阅读和删除cookie的基本代码,如下所示:

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else
        var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    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, c.length);
        if (c.indexOf(nameEQ) == 0)
            return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

我创建了这样的动态命名cookie:

if ($(".timed-top-message").size() > 0) {
    $(".timed-top-message").on("click", "i", function() {
        var CookieUniqueIdentifier = $(this).parent().attr("id")
        $(this).parent().fadeOut(200);

        createCookie(CookieUniqueIdentifier, 'true', 100000)
        console.log('cookie created');
    });
}

这就完成了这项工作。我的问题是我必须阅读cookie。这会引发错误:

(function() {
    var checkForCookiez = readCookie(CookieUniqueIdentifier); // i read the cookie
    if (!checkForCookiez) { // if it doesn't exist
        console.log('it does not exist')
    } else{ // if it does exist
        console.log('it does exist')
    }
})();

错误是

app.js:1142 Uncaught ReferenceError: CookieUniqueIdentifier is not defined

我得到CookieUniqueIdentifier的范围是在点击功能中,它无法检索它。但我想要实现的是一个以独特的id命名的dinamically创建cookie的系统,并因此以动态的方式阅读它们。

我对jquery不是很好,我想知道我是否走在正确的道路上。任何建议都非常感谢。

1 个答案:

答案 0 :(得分:0)

我认为这里最好的方法是在显示警报消息之前读取cookie(在页面加载时),并且仅在cookie不存在时显示警报。您还没有显示部分代码,但如果您包含该代码,我很乐意在此处添加相关代码更新。