首页 > 代码库 > JS封装Cookie

JS封装Cookie

/* @黑眼诗人 <www.chenwei.ws> */<script>//设置cookie: cookie名,cookie值,天数function setCookie(name, value, iDay){  var oDate = new Data();  oDate.setDate(oDate.getDate() + iDay);  document.cookie = name+ ‘=‘ +value+ ‘; expires = ‘+oDate}//获取cookiefunction getCookie(name){  var arr = document.cookie.split(; ); //将cookie切割成数组  for(var i = 0; i < arr.length; i++)  {   var arr2 = arr[i].split(‘=‘); //数组元素以等号切割    if(arr2[0] == name)    {     return arr2[1]; //获取cookie名对应的cookie值    }  }  return ‘‘; //如果没有获取到值,返回空字符串}//删除cookiefunction removeCookie(name){ setCookie(name, 1, -1);}//页面载入时执行window.onload = function (){  var oForm = document.getElementById(‘form‘);  var oUser = document.getElementsByName(‘user‘)[0];  oForm.onsubmit = function ()  {   setCookie(‘user‘, oUser.value, 14); //提交的时候设置cookie  }  oUser.value = getCookie(‘user‘); //载入页面时设置user值}</script><form id="form" action="http://www.chenwei.ws">  用户名:<input type="text" name="user" /><br />  密码:<input type="password" name="pass" /><br />  <input type="submit" value="http://www.mamicode.com/登录"></form>

原文:http://www.cnblogs.com/farwish/p/3812956.html