jQuery 检查 Cookie 是否存在,如果不存在则创建它 [英] jQuery check if Cookie exists, if not create it
问题描述
我无法让这段代码工作,我一定遗漏了一些非常简单的东西.我正在尝试检查 Cookie 是否存在,如果它不{创建它},它是否{不做任何事}.我正在通过在页面上包含警报来测试 cookie.基本上我不希望 cookie 继续使用推荐 URL 重新创建,我试图只获取第一个被推荐的 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
}
检查 null、空或未定义变量的类型总是返回 'undefined'
Checking the type of a null, empty or undefined var always returns 'undefined'
您可以更轻松地到达那里:
You can get there even easier:
if (!!$.cookie('token')) {
// have cookie
} else {
// no cookie
}
!!
将把 falsy 值 为假.请记住,这会将 0
变为 false!
!!
will turn the falsy values to false. Bear in mind that this will turn 0
to false!
这篇关于jQuery 检查 Cookie 是否存在,如果不存在则创建它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!