jQuery 检查 Cookie 是否存在,如果不存在则创建它
我无法让这段代码工作,我一定错过了一些非常简单的东西。我试图检查 Cookie 是否存在,如果它不{创建它},则不执行任何操作。我正在通过在页面上添加警报来测试 cookie。基本上我不希望 cookie 继续使用引用 URL 重新创建,我试图仅获取第一个引用 URL。
$(document).ready(function(){
if ($.cookie('bas_referral') == null ){
var ref = document.referrer.toLowerCase();
// set cookie
var cookURL = $.cookie('bas_referral', ref, { expires: 1 });
}
});
显示当前cookie内容:
// get cookie
alert($.cookie('bas_referral'));
// delete cookie
$.cookie('bas_referral', null);
I cannot get this code to work I must be missing something pretty simple. I am trying to check to see if a Cookie exists, if it does {do nothing} if it doesn't {create it}. I am testing the cookie by including an alert on a page. Basically I do not want the cookie to keep re-creating with a referral url, I am trying to grab only the FIRST referred URL.
$(document).ready(function(){
if ($.cookie('bas_referral') == null ){
var ref = document.referrer.toLowerCase();
// set cookie
var cookURL = $.cookie('bas_referral', ref, { expires: 1 });
}
});
Displaying the current cookie contents:
// get cookie
alert($.cookie('bas_referral'));
// delete cookie
$.cookie('bas_referral', null);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为万无一失的方法是:
检查 null、空或未定义 var 的类型始终返回“未定义”
编辑:
您可以更轻松地到达那里:
!!
会将 falsy 值为 false。请记住,这会将0
变为 false!I think the bulletproof way is:
Checking the type of a null, empty or undefined var always returns 'undefined'
Edit:
You can get there even easier:
!!
will turn the falsy values to false. Bear in mind that this will turn0
to false!我在这方面遇到了很多麻烦,因为我正在使用:
无论我在设置 cookie 方面做了什么,上面的内容总是返回 false。从我的测试看来,该对象在设置之前似乎是未定义的,因此将以下内容添加到我的代码中可以修复它。
I was having alot of trouble with this because I was using:
The above was ALWAYS returning false, no matter what I did in terms of setting the cookie or not. From my tests it seems that the object is therefore undefined before it's set so adding the following to my code fixed it.
您可以在检查 cookie 是否存在并为其赋值后设置它。
You can set the cookie after having checked if it exists with a value.
尝试一下这个非常简单的方法:
Try this very simple: