分享JS封装的Cookie创建、获取、删除函数
以下是一个简单的JavaScript封装Cookie创建、获取、删除函数的示例: ```javascript function setCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i
创建Cookie
functionsetCookie(key,value,time){vartimes=newDate();//获取当前的时间times.setDate(times.getDate()+time);//设置时间document.cookie=key+'='+value+';expires='+times;//在cookie中创建}
获取Cookie
functiongetCookie(key){varcookie_=document.cookie;//拿到cookie中的所有数据是一个字符串varcookie_arr=cookie_.split(';');//以;和空格分割成数组for(varkofcookie_arr){//循环遍历数组cookie_arrforof遍历取到值varres=k.split('=');//以等号再次进行分割if(res[0]==key){returnres[1];}}}
删除Cookie
functionremoveCookie(key){this.setCookie(key,'',-1);//再次调用创建函数把时间改为负数就等于删除}