Home  >  Article  >  Web Front-end  >  How to use cookies to record user names in js_javascript skills

How to use cookies to record user names in js_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:29:361429browse

The example in this article describes how js uses cookies to record user names. Share it with everyone for your reference, the details are as follows:

Cookie idea: When you click the login button, save the cookie, and read the cookie when you visit again, that is, just save the cookie value before setting the txt value.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
function setCookie(name, value, iDay)
{
  var oDate=new Date();
  oDate.setDate(oDate.getDate()+iDay); //用来设置过期时间用的,获取当前时间加上传进来的iDay就是过期时间
  document.cookie=name+'='+value+';expires='+oDate;
};
function getCookie(name)
{
  var arr=document.cookie.split('; '); //多个cookie值是以; 分隔的,用split把cookie分割开并赋值给数组
  for(var i=0;i<arr[i].length;i++) //历遍数组
  {
    var arr2=arr[i].split('='); //原来割好的数组是:user=simon,再用split('=')分割成:user simon 这样可以通过arr2[0] arr2[1]来分别获取user和simon 
    if(arr2[0]==name) //如果数组的属性名等于传进来的name
    {
      return arr2[1]; //就返回属性名对应的值
    }
    return ''; //没找到就返回空
  }
};
function removeCookie(name)
{
  setCookie(name, 1, -1); //-1就是告诉系统已经过期,系统就会立刻去删除cookie
};
window.onload=function()
{
  var form=document.getElementById('form');
  var user=document.getElementsByName('user')[0];
  form.onsubmit=function()
  {
    setCookie('user', user.value, 14);
  };
  user.value=getCookie('user');
};
</script>
</head>
<body>
<form action="" id="form">
  用户名:<input type="text" name="user" /><br />
  密码:<input type="password" name="pass" /><br />
  <input type="submit" value="登录" />
</form>
</body>
</html>

I hope this article will be helpful to everyone in JavaScript programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn