原生js登录创建cookie

原生js创建cookie,功能:点击登录按钮时,将用户名、密码存为cookie;页面再次加载时,自动读取cookie中的用户名、密码。

<html>
<head>
<title>cookies</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function setCookie(name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());//创建cookie
}

function getCookie(name)//获取cookie
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(name + "=");
if (c_start!=-1)
{
c_start=c_start + name.length+1 ;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}

function checkCookie()//检查cookie是否存在,若存在,读取出来
{
var userName=document.getElementById("userName");
var password=document.getElementById("password");
var UValue=getCookie(userName.id);
var PValue=getCookie(password.id);
if (UValue!=null && UValue!="" && PValue!=null && PValue!="")
{
userName.value=UValue;
password.value=PValue;
}
}

function saveCookie(){//保存cookie
var UName=document.getElementById("userName");
var PName=document.getElementById("password");
if(UName.value==""){
alert("请输入用户名!");
}
else if(PName.value==""){
alert("请输入密码!");
}
else if(confirm("是否保存用户名密码?")){
setCookie(UName.id,UName.value,30);
setCookie(PName.id,PName.value,30);
}
}
</script>
</head>

<body onload="checkCookie()">
<input id="userName" type="text" name="" placeholder="用户名" value="">
<input id="password" type="password" name="" placeholder="密码" value="">
<input type="button" name="" value="登录" onclick="saveCookie()">
</body>
</html>

原文地址:https://www.cnblogs.com/chenyoumei/p/7458629.html