0

我有一组用作警报的热门消息。他们有一个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的范围是点击函数,它无法检索它。但我想要实现的是一个系统,可以动态地创建由唯一名称命名的 cookie id,从而以动态方式读取它们。

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

4

1 回答 1

0

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

于 2017-01-03T15:56:22.893 回答