// 设置 function setCookie(c_name, value, expiredays) { var exdate = new Date(); exdate.setTime(Number(exdate) + expiredays); document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()); } // 获取 (获取不到对应key的内容,就返回"") function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "=");//获取字符串的起点 if (c_start != -1) { c_start = c_start + c_name.length + 1;//获取值的起点 c_end = document.cookie.indexOf(";", c_start);//获取结尾处 if (c_end == -1) c_end = document.cookie.length;//如果是最后一个,结尾就是cookie字符串的结尾 return decodeURI(document.cookie.substring(c_start, c_end));//截取字符串返回 } } return ""; } // 删除 function removeCookie(sName) { setCookie(sName, 1, -1); } setCookie('test', 'testContent') // 不设置过期时间,关闭浏览器就过期 setCookie('test','1111',20*1000) // 20秒过期 console.log(getCookie('test')); console.log(removeCookie('test'));