cookie记录用户名

在说如何用cookie记录用户名之前,我们先来说说cookie的工作原理:

  • alert(typeof oDate.toGMTString()); (把日期对象转成字符串的形式)
 function getCookie(key) {   
   var arr1 = document.cookie.split('; ');  (username=win; age=23,把数据从分号开始拆成一个个cookie)
   for (var i=0; i<arr1.length; i++) {   (循环cookie)   
   var arr2 = arr1[i].split('=');     (username=win,,把数据从等号开始拆分) 
   if ( arr2[0] == key ) {         (判断截取的cookie值是否和key值相等)
   return decodeURI(arr2[1]);      
       }  
    }
 }
function setCookie(key, value, t) {   
 var oDate = new Date();   
 oDate.setDate( oDate.getDate() + t );   
 document.cookie = key + '=' + value + ';expires=' + oDate.toGMTString();
}
 function removeCookie(key) {   
  setCookie(key, '', -1);
}
传参运行测试:

setCookie('sex','男', 10););

removeCookie('username');

removeCookie('age');

removeCookie('sex');

完整示例:
 <script>
  window.onload = function() {      
  var oUsername = document.getElementById('username');   
  var oLogin = document.getElementById('login');   
  var oDel = document.getElementById('del');      
  if ( getCookie('username') ) {      
     oUsername.value = getCookie('username');   
  }      
 oLogin.onclick = function() {           
   alert('登陆成功');      
   setCookie('username', oUsername.value, 5);         
}     
   oDel.onclick = function() {      
   removeCookie('username');      
   oUsername.value = '';   
   }   
}
function getCookie(key) {   
   var arr1 = document.cookie.split('; ');  (username=win; age=23,把数据从分号开始拆成一个个cookie)
   for (var i=0; i<arr1.length; i++) {   (循环cookie)   
   var arr2 = arr1[i].split('=');     (username=win,,把数据从等号开始拆分) 
   if ( arr2[0] == key ) {         (判断截取的cookie值是否和key值相等)
   return decodeURI(arr2[1]);      
       }  
    }
 }
function setCookie(key, value, t) {   
 var oDate = new Date();   
 oDate.setDate( oDate.getDate() + t );   
 document.cookie = key + '=' + value + ';expires=' + oDate.toGMTString();
}
function removeCookie(key) {  
   setCookie(key, '', -1);
}
</script>
<body>   
  <input type="text" id="username" />    
  <input type="button" value="登陆" id="login" />    
 <input type="button" value="删除" id="del" />
</body>

分享技术,分享快乐!

 

posted @ 2017-01-03 16:27  win.w  阅读(1478)  评论(0编辑  收藏  举报