项目描述
上传时间
浏览人数
(1)添加Cookie
代码:
let u = {name:"Vernon", age:18, job:"web design"}; //添加Cookie setCookie("userInfo",JSON.stringify(u),1); setCookie("Tom","19",1) setCookie("computerLanguage","Java",2) function setCookie(cName, cVal, expireDays){ if(cName && cVal){ cName = cName.replace(/\s+/g, "");//根据正则表达式把空格替换成"",相当与去空格 cVal = cVal.trim("");//去掉首位空格 let date = new Date(); console.log(date.getTime()); let t = date.getTime() + expireDays * 24 * 60 * 60 *1000;//生成时间戳+两天的毫秒数 date.setTime(t); let utc = date.toUTCString(); console.log(utc); document.cookie = cName + "=" + cVal + ";expires=" + utc + ";path=/"; } }
(2)查看Cookie
代码:
let cV = getCookie("userInfo"); console.log(cV); function getCookie(cName){ //console.log(document.cookie); if(!cName){ return ""; } let arr = document.cookie.split("; ");// cName += "="; for (let i = 0; i <arr.length ; i++) { if(arr[i].startsWith(cName)){//每个cookie整体生成的是个字符串"key=value" return arr[i].substring(cName.length);// } } return ""; }
(3)删除Cookie
代码:
function setCookie(cName, cVal, expireDays){ if(cName && cVal){ cName = cName.replace(/\s+/g, "");//根据正则表达式把空格替换成"",相当与去空格 cVal = cVal.trim("");//去掉首位空格 let date = new Date(); console.log(date.getTime()); let t = date.getTime() + expireDays * 24 * 60 * 60 *1000;//生成时间戳+两天的毫秒数 date.setTime(t); let utc = date.toUTCString(); console.log(utc); document.cookie = cName + "=" + cVal + ";expires=" + utc + ";path=/"; } } setCookie("Tom","12",0);
(4)修改Cookie
代码:
function setCookie(cName, cVal, expireDays){ if(cName && cVal){ cName = cName.replace(/\s+/g, "");//根据正则表达式把空格替换成"",相当与去空格 cVal = cVal.trim("");//去掉首位空格 let date = new Date(); console.log(date.getTime()); let t = date.getTime() + expireDays * 24 * 60 * 60 *1000;//生成时间戳+两天的毫秒数 date.setTime(t); let utc = date.toUTCString(); console.log(utc); document.cookie = cName + "=" + cVal + ";expires=" + utc + ";path=/"; } } setCookie("computerLanguage","C++",2)
代码虐我千百遍 我对代码初恋