cookie的封装
1 function setCookie(key,value,extime=0){ 2 let exp = 0;//设置时间 3 if(extime==0){//不需要设置过期时间 4 exp = null; 5 }else{ 6 let d = new Date(); 7 let time = d.getTime(); 8 //过期时间以分钟为单位 9 d.setTime(time+extime*60*1000); 10 exp = d.toGMTString(); 11 } 12 //cookie设置 13 document.cookie = key + '=' + value + ';expires=' + exp; 14 } 15 16 //cookie获取的封装 17 function getCookie(key){ 18 //获取所有的cookies 19 let cookies = document.cookie; 20 //分割cookie 21 let cookArr = cookies.split(';'); 22 23 for(var i = 0;i<cookArr.length;i++){ 24 //将key和value进行分割 25 let tmpArr = cookArr[i].split('='); 26 //去除key前面的空格 27 tmpArr[0] = tmpArr[0].replace(/^\s*/,''); 28 if(key == tmpArr[0]){//比对key,如果相等,就表示当前用户就是获取这个key的值 29 return tmpArr[1];//返回value值 30 } 31 } 32 33 }