【问题标题】:Set cookie only when onclick and hide the message仅在单击时设置 cookie 并隐藏消息
【发布时间】:2015-03-01 20:14:46
【问题描述】:

我正在尝试在页面上设置 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');
}

还有我的工作 jsfiddle:http://goo.gl/61aLuS

【问题讨论】:

  • #close-cookies 是您的“我接受”按钮的 id 吗?

标签: javascript jquery cookies setcookie


【解决方案1】:

这段代码设置了 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');
});

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 2014-08-02
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多