创建cookie Javascript

时间:2014-10-03 08:45:28

标签: javascript jquery cookies

当用户点击按钮时,我必须创建一个JS cookie,这个cookie会在10分钟后用另一个弹出窗口记住他。

示例:

<button>Click me!</button>

,用户点击时按钮将隐藏,10分钟后按钮将再次显示:

<button>Click me!</button>

脚本部分:

function setCookieMsg(name) {
        var d = new Date();
        var time = d.setTime(d.getTime() + (600000));
        document.cookie = name + "=" + time;
    }

    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) != -1) return c.substring(name.length, c.length);
    }
    return "";
    }

    function checkCookieMsg() {
    var cookie = getCookie("name");
    var d = new Date() - 600000;
    if (cookie == "") {
        setCookie("name", cookie);
    }else if (d => cookie) {
        $().getUnReadMessage();
        }
    }

我错了什么?

1 个答案:

答案 0 :(得分:0)

您没有提及Cookie中的到期日期。到期日期应为UTC时间字符串。

function setCookieMsg(name) {
     var date = new Date();
     date.setTime(date.getTime()+(600000));
     var expires = "; expires="+date.toUTCString();
     document.cookie = name + "=" + expires;
}