jQuery检查Cookie是否存在,如果没有创建它
我无法得到这个代码工作我必须缺少一些很简单。我试图检查,如果一个Cookie存在,如果它{做什么}如果它不{建立}。我正在通过在页面上添加提醒来测试Cookie。基本上我不想让cookie继续使用引用网址重新创建,我试图只抓住第一个引用的URL。
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 });
}
});
显示目前的Cookie内容:
Displaying the current cookie contents:
// get cookie
alert($.cookie('bas_referral'));
// delete cookie
$.cookie('bas_referral', null);
我认为防弹的方法是:
if (typeof $.cookie('token') === 'undefined'){
//no cookie
} else {
//have cookie
}
检查类型空值或未定义的var始终返回'undefined'
Checking the type of a null, empty or undefined var always returns 'undefined'
编辑:
您可以更轻松地访问:
You can get there even easier:
if (!!$.cookie('token')) {
//no cookie
} else {
// have cookie
}
会将 falsy 值改为假。请记住,这会将 0
更改为false!
!!
will turn the falsy values to false. Bear in mind that this will turn 0
to false!