JS封装Cookie

时间:2024-09-29 16:06:14
/* @黑眼诗人 <www.farwish.com> */
<script>
//设置cookie: cookie名,cookie值,天数
function setCookie(name, value, iDay)
{
  var oDate = new Data();
  oDate.setDate(oDate.getDate() + iDay);
  document.cookie = name+ '=' +value+ '; expires = '+oDate
} //获取cookie
function 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 ''; //如果没有获取到值,返回空字符串
} //删除cookie
function 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="登录">
</form>