仅当onclick和隐藏消息时设置cookie

Set cookie only when onclick and hide the message

本文关键字:设置 cookie 消息 隐藏 onclick 仅当      更新时间:2023-09-26

我正在尝试在页面上设置cookie消息。我想要的是当cookie不存在时,会显示消息。当用户点击"我接受"按钮时,cookie就被设置好了。当用户返回页面/网站时,该消息将不再显示。

但它现在所做的是在用户访问we页面时立即设置cookie。

$(document).ready(function() {

    var visit=GetCookie("AMIR86");
    if (visit==null){
        cookiebar();
    }
    var expire=new Date();
    expire=new Date(expire.getTime()+7776000000);
    document.cookie="AMIR86=here; expires="+expire;

    $('#close-cookies').click(function(){ 
        $('#cookiebar').addClass('close-cookies');
    });
});
function GetCookie(name) {
    var arg=name+"=";
    var arglen=arg.length;
    var dclen=document.cookie.length;
    var i=0;
    while (i<dclen) {
        var j=i+arglen;
            if (document.cookie.substring(i,j)==arg)
                return "here";
                i=document.cookie.indexOf(" ",i)+1;
            if (i==0) 
                break;
    }
    return null;
}
function cookiebar() {
    $('#cookiebar').addClass('display');
}

和我的工作小提琴:http://goo.gl/61aLuS

这段代码设置cookie。为了可读性和清晰的编码实践,将其移动到自己的函数中。

function setAgreeCookie() {
    var expire=new Date();
    expire=new Date(expire.getTime()+7776000000);
    document.cookie="AMIR86=here; expires="+expire;
}

然后,在"我同意"按钮上设置一个click处理程序来设置cookie。

$('#close-cookies').click(function(){ 
    setAgreeCookie();
    $('#cookiebar').addClass('close-cookies');
});