2

我正在努力在我的网站上制作横幅,以告知访问者有关 cookie 的信息。我想使用 jquery 应用此横幅,当人们单击“确定”时,它应该会消失。那部分我可以做,但如果他们在 24 小时后再次访问该网站,我希望它重新出现。我想我可以用 cookie 做到这一点,但我不太确定如何去做。谁能指出我正确的方向?

4

4 回答 4

1

JQuery 没有内置的 cookie 处理程序,但在常规 js 中确实没有那么难。正如@Tim 所提到的,这是糟糕的用户体验设计,你不应该用这样的弹出窗口来惹恼人们。一次就够了。但我理解为什么您可能希望确保它不会每次都弹出。如果您愿意,您可以将日期设置为非常遥远的日期,以帮助防止它再次出现,直到用户清除其中的 cookie。

像这样设置cookie

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

并像这样检索它。

function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
  {
  c_start = c_value.indexOf(c_name + "=");
  }
if (c_start == -1)
  {
  c_value = null;
  }
else
  {
  c_start = c_value.indexOf("=", c_start) + 1;
  var c_end = c_value.indexOf(";", c_start);
  if (c_end == -1)
  {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}

你可以像这样使用整个东西......

function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }

*直接取自这里http://www.w3schools.com/js/js_cookies.asp * }

于 2013-09-04T17:40:10.410 回答
1

我会使用 localStorage,在点击时添加当前日期:

var curDate = new Date();

$('#Button').on('click',function(){
    localStorage['banner'] = curDate.getDate();
});

然后检查它是否存在,并比较日期:

if(localStorage['banner'].length > 0){
    var future = new Date();
    future.setDate(localStorage['banner'] + (24 * 60 * 60 * 1000));

    if(future > curDate){
        localStorage['banner'].length = 0;
    }
}

如果他们使用相同的浏览器,这将起作用,就像 cookie 一样。请注意,这仅适用于 IE8 及更高版本,仅包含全球 99.2% 的用户。

于 2013-09-04T17:44:04.217 回答
0

您可以通过编写一个非常简单的freshVistor(howFresh)函数来解决这个问题,该函数接受一个可选参数来定义您认为“新鲜”的新鲜程度。

function freshVisitor(howFresh) {
    var namespace = 'freshVisitorSOCookie';
    if (readCookie(namespace)) {
        return false;
    }
    return makeCookie(namespace, 'yes', {
        expires: howFresh || 1
    });
}

您的应用程序可以使用如下freshVisitor()函数:

if (freshVisitor()) {
    /* This means the user is new or has not visited within 1 day
     * So show your banner or do something that you want to do */
} else {
    /* The user has visited already within the previous day
     * or has disabled cookies. */
}

您还可以指定自己的“新鲜”定义:

if (freshVisitor(2)) ... /* uses a 2-day period to calculate freshness */

请注意!为了用户友好,我让这个功能在用户禁用 cookie 时自动返回 false,以防止没有 cookie 的人被横幅广告淹没。我相信这是对待访问我网站的人的正确方式,但如果您希望扭转这种尊重行为,请随时调整我的freshVisitor()代码中的逻辑。

当然,您需要适当的 cookie 函数来使用上面的符号计算过期日期,所以这里是完整的代码:

<script>
    function makeCookie(name, value, p) {
        var s, k;

        function reldate(days) {
            var d;
            d = new Date();
            d.setTime(d.getTime() + days * 86400000);
            return d.toGMTString();
        }
        s = escape(name) + '=' + escape(value);
        if (p)
            for (k in p) {

                /* convert a numeric expires value to a relative date */

                if (k == 'expires')
                    p[k] = isNaN(p[k]) ? p[k] : reldate(p[k]);

                /* The secure property is the only special case
here, and it causes two problems. Rather than
being '; protocol=secure' like all other
properties, the secure property is set by
appending '; secure', so we have to use a
ternary statement to format the string.

The second problem is that secure doesn't have
any value associated with it, so whatever value
people use doesn't matter. However, we don't
want to surprise people who set { secure: false }.
For this reason, we actually do have to check
the value of the secure property so that someone
won't end up with a secure cookie when
they didn't want one. */

                if (p[k])
                    s += '; ' + (k != 'secure' ? k + '=' + p[k] : k);
            }
        document.cookie = s;
        return readCookie(name) == value;
    }

    function readCookie(name) {
        var s = document.cookie,
            i;
        if (s)
            for (i = 0, s = s.split('; '); i < s.length; i++) {
                s[i] = s[i].split('=', 2);
                if (unescape(s[i][0]) == name)
                    return unescape(s[i][1]);
            }
        return null;
    }

    function removeCookie(name) {
        return !makeCookie(name, '', {
            expires: -1
        });
    }

    function freshVisitor(howFresh) {
        var namespace = 'freshVisitorSOCookie';
        if (readCookie(namespace)) {
            return false;
        }
        return makeCookie(namespace, 'yes', {
            expires: howFresh || 1
        });
    }

    document.write('Fresh visitor status: ', freshVisitor());
</script>
于 2013-09-04T18:06:14.287 回答
0

对于更少的代码,更简单的实现试试这个:

jQuery.cookie

例子:

创建一个cookie:

$.cookie('the_cookie', 'the_value');

读取 cookie:

var cookieval = $.cookie('the_cookie');

创建一个即将过期的 cookie(7 天后过期):

$.cookie('the_cookie', 'the_value', { expires: 7 });

资源

于 2013-09-04T17:45:20.790 回答