Cookie技术也叫会话跟踪技术,是指在一次会话从开始到结束的整个过程,全程跟踪记录客户端的状态(例如:是否登录、购物车信息、是否已下载、是否已点赞、视频播放进度等等)

cookie的参数:键、值、有效期、路径

下面是对Cookie的创建、获取、删除的函数封装

创建Cookie的封装
function createCookie(key,value,expires,path){
var cookieText = encodeURIComponent(key)+”=”+encodeURIComponent(value);
if(typeof expires == number){
var date = new Date();
date.setDate(date.getDate()+expires);
cookieText += “;expires=”+date;
}
if(path){
cookieText += “;path=”+path;
}
document.cookie = cookieText;
}
//获取cookie方法一
function getCookie(key){
var cookieText = encodeURIComponent(key)+”=”;
var start = document.cookie.indexOf(“cookieText”);
if(start!=-1){
var end = document.cookie.indexOf(“;”,start);
if(end == -1){
end = document.cookie.length;
}
}
return decodeURIComponent(document.cookie.substring(start+cookieText.length,end));
}
//获取Cookie方法二
function gainCookie(key){
var arr = document.cookie.split(“; “);
for(var i = 0;i< arr.length;i ++){
var list = arr[i].split(“=”)
if(list[0] ==key){
return decodeURIComponent(list[1]);
}
}
}

 //删除Cookie
 function remove(key,path){
   if(path){
     document.cookie = encodeURIComponent(key)+"=expires="+new Date(0)+";path="+path;
   }
   else{
     document.cookie = encodeURIComponent(key)+"=expires="+new Date(0);
   }
                                   }​

本文转载:CSDN博客