1. 程式人生 > >js中cookie操作

js中cookie操作

get [1] 查詢 turn == 時間 date add doc

1.設置cookie

function addCookie(name,value,expireHours){
  var cookieString=name+"="+escape(value)+"; path=/";
  //判斷是否設置過期時間
  if(expireHours>0){
    var date=new Date();
    date.setTime(date.getTime()+expireHours*3600*1000);
    cookieString=cookieString+";expires="+date.toGMTString();
  }
  document.cookie=cookieString;
}

2.查詢cookie

function getCookie(name){
  var strcookie=document.cookie;
  var arrcookie=strcookie.split("; ");
  for(var i=0;i<arrcookie.length;i++){
    var arr=arrcookie[i].split("=");
    if(arr[0]==name)return unescape(arr[1]);
  }
  return null;
}

3.刪除cookie

function delCookie(name){//刪除cookie
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval=getCookie(name);
  if(cval!=null) document.cookie= name + "="+cval+"; path=/;expires="+exp.toGMTString();
}

js中cookie操作