jQuery检查Cookie是否存在,如果没有创建它 [英] jQuery check if Cookie exists, if not create it

查看:979
本文介绍了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!

这篇关于jQuery检查Cookie是否存在,如果没有创建它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆