<!DOCTYPE HTML> <html lang="zh"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <meta name="applicable-device" content="pc,mobile"/> <meta name="renderer" content="webkit"/> <meta name="keywords" content=""/> <meta name="description" content=""/> <title>cookie与封装</title> </head> <body> <script src="http://s0.ifengimg.com/static/js/jquery-1.7.2.min_c4de8813.js"></script> <script> var cookieUtil={ set:function(name,value,expires,path,domain,secure){//设置cookie var cookieName=encodeURIComponent(name)+‘=‘+encodeURIComponent(value); if(expires instanceof Date){ cookieName+= ‘;expires=‘+expires; } if(path){ cookieName+= ‘;path=‘+path; } if(domain){ cookieName+= ‘;domain=‘+domain; } if(secure){ cookieName+= ‘;secure‘; } document.cookie=cookieName; }, setDate:function(day){//设置过期时间 var date=null; if(typeof day ==‘number‘ && day>0){ date=new Date(); date.setDate(date.getDate()+day); }else{ throw new Error(‘你输入的天数不合法,请输入大于0的数字‘); } return date; }, get:function(name){//获取cookie var cookieName=encodeURIComponent(name)+‘=‘, cookieStart, cookieValue; cookieStart=document.cookie.indexOf(cookieName); if(cookieStart>-1){ var cookieEnd=document.cookie.indexOf(‘;‘,cookieStart); if(cookieEnd == -1){ cookieEnd=document.cookie.length; } cookieValue=decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd)); } return cookieValue; }, unSet:function(name,path,domain,secure){//删除cookie cookieUtil.set(name,‘‘,new Date(0),path,domain,secure); } }; //测试设置cookie /*cookieUtil.set(‘use‘,‘xiangcy‘,cookieUtil.setDate(1)); cookieUtil.set(‘url‘,‘ycvo.com‘,cookieUtil.setDate(28)); cookieUtil.set(‘email‘,‘[email protected]‘);*/ //测试删除cookie /* cookieUtil.unSet(‘use‘); cookieUtil.unSet(‘url‘); cookieUtil.unSet(‘email‘); */ //测试获取cookie alert(cookieUtil.get(‘use‘)); alert(cookieUtil.get(‘url‘)); alert(cookieUtil.get(‘email‘)); </script> </body> </html>
时间: 2024-10-17 06:50:20