jQuery 为第一次访问设置 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9173947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery set cookie for first visit
提问by arekk
I got a script like that (I use jQuery cookie jsto set cookies) to display layer on first visit.
我有一个这样的脚本(我使用jQuery cookie js来设置 cookie)来在第一次访问时显示层。
<script type="text/javascript">
$(document).ready(function() {
var visited = $.cookie('visited', 'yes', { expires: 1, path: '/' });
if (visited == null) {
$('.newsletter_layer').show();
$.cookie('visited', 'yes');
alert($.cookie("visited"));
}
});
</script>
Unfortunatelly something is not working. I think something is wrong with the if statement. Anyone have idea what can be wrong?
不幸的是,有些东西不起作用。我认为 if 语句有问题。任何人都知道什么可能是错的?
回答by Rory McCrossan
Because you are creating the cookie, it will never be null. You need to change your logic to first check if the cookie exists. If not, show the .newsletter_layer
element, then set the cookie value:
因为您正在创建 cookie,所以它永远不会为空。您需要更改逻辑以首先检查 cookie 是否存在。如果没有,则显示该.newsletter_layer
元素,然后设置 cookie 值:
<script type="text/javascript">
$(document).ready(function() {
// check cookie
var visited = $.cookie("visited")
if (visited == null) {
$('.newsletter_layer').show();
alert($.cookie("visited"));
}
// set cookie
$.cookie('visited', 'yes', { expires: 1, path: '/' });
});
</script>
回答by JDM_trash
If somebody stumbles across this 6 years into the future like I, I got this to work with modification:
如果有人像我一样在未来的 6 年中偶然发现,我会修改以下内容:
Replace: $.cookie -> Cookies
替换:$.cookie -> Cookies