js使用cookie实现记住用户名功能示例

2019/6/26 22:59:31

本文主要是介绍js使用cookie实现记住用户名功能示例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本文实例讲述了js使用cookie实现记住用户名功能。分享给大家供大家参考,具体如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>www.zyiz.net cookie记住用户名</title>
<meta name="description" content="">
<meta name="keywords" content="">
</head>
<body>
 <script>
 //1、cookie的使用:document.cookie = 'key=value';可以同时设置多个
 // document.cookie="username=longzhoufeng"
// document.cookie="age=03"
//2、cookie的过期时间:document.cookie = '名称=值;expires=' + 字符串格式的时间;
// var myDate=new Date()
// myDate.setDate(myDate.getDate()+3)
// document.cookie="mynameis="+encodeURI("longzhoufeng")+ ";expires="+myDate.toGMTString();
// document.cookie="age=30"
// console.log(decodeURI(document.cookie))
// 解码后输出结果如下:
//mynameis=longzhoufeng; age=30
//3、把上面的封装成一个函数,其中有三个参数是在变化的,key值,value值,T时间
function setCookie(key,value,t){
  var myDate=new Date()
  myDate.setDate(myDate.getDate()+t)
  document.cookie=key+"="+value+ ";expires="+myDate.toGMTString();
}
function getCookie(key){
  var arr1 = document.cookie.split('; ');
  for (var i=0; i<arr1.length; i++) {
    var arr2 = arr1[i].split('=');
    if ( arr2[0] == key ) {
      return decodeURI(arr2[1]);
    }
  }
}
function removeCookie(key) {
  setCookie(key, '', -1);
}
// setCookie("myName","longzhoufeng",1)
// console.log(getCookie("myName"))
// console.log(removeCookie("myName"))
// alert(typeof myDate)
// 必须将时间格式转换成字符形式
// alert(typeof myDate.toGMTString());
//4、内容最好编码存放,encodeURI
//alert( encodeURI('你好') );
//alert( decodeURI('%E4%BD%A0%E5%A5%BD') )
 </script>
 <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 = '';
  }
}
 </script>
  <input type="text" id="username" />
    <input type="button" value="登陆" id="login" />
    <input type="button" value="删除" id="del" />
</body>
</html>

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》及《JavaScript数学运算用法总结

希望本文所述对大家JavaScript程序设计有所帮助。



这篇关于js使用cookie实现记住用户名功能示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程