对于学习前端的同学,想必或多或少在其他网页上也见识到其他网页上的记住密码功能,其实是利用Cookie来实现。而我经过多次百度查询,也摸索出来该如何利用Cookie来实现。(代码来源于网上,加上我部分更改,侵权联系,必删)
在script标签内(html5)
window.onload=function onLoginLoaded () {
if(checkCookie()){
//获取Cookie
var info = getCookie();
var ca = info.split(",");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
if (c.substring(0, 8) === "account=") {//截取字符串account=
//alert(c.substring(8));
document.getElementById("account").value = c.substring(8);
} else if (c.substring(0, 9) === "password=") {//截取字符串password=
//alert(c.substring(9));
document.getElementById("password").value = c.substring(9);
}
}
}
};
该js函数是为了实现你打开该网页或者刷新该网页时,执行的函数。主要代码是实现检查Cookie是否为空,若不为空,就把Cookie提取出来并加以解析。
其中ca是个字符串数组,其作用是储存Cookie中分割的字符串。(假设我的Cookie存的是:account=1234,password=4567,time=,则会分割出三个字符串,分别为:account=1234,password=4567,time=)之后便根据你需要提取出你想要的数据。
之后再通过document.getElementById(“文本框的id名”)来对你指定的文本框赋值
function Stuts() {
if(document.getElementById('chkRememberPwd').checked === true){
return true;
}else{
return false;
}
}
function SetPwbAndChk() {
//判断记住密码是否被勾选
// var checkstatus = document.getElementById('chkRememberPwb');
if(Stuts() === true){
//获取用户名
var usr = document.getElementById('account').value;
//获取密码
var pwb = document.getElementById("password").value;
//alert(pwb+"密码"); //测试密码
var expdate = new Date();
//设置Cookie过期时间为两周
expdate.setTime(expdate.getTime() + 14 * (24*60*60*1000));
var time =expdate.toUTCString();
//写进Cookie
document.cookie = "account="+usr+","+"password"+"="+pwb+","+"expdate="+ time+";path=/";
}else{
var expdate = new Date();
expdate.setTime(0);
var time =expdate.toUTCString();
document.cookie = "account="+",password=,"+"expdate="+ time+";path=/";
}
}
Stuts()函数只是判断你的记住密码的框是否被勾选(假设你记住密码的框的id名称为’chkRememberPwb’)。
SetPwbAndChk()函数实现的是假设你勾选记住密码,点击登录后便会将信息储存到你的Cookie(假设你也想设置Cookie的储存值为"account=,password=,expdate="),其中expdate为该Cookie的保质期。如果不勾选,便清空Cookie(具体操作为将expdate设置成0,也就是使其过期)。另外注意,分割符不一定要是",",也可以是其他,如果你使用Cookie时发现只显示"account=“加上你的账户信息,可以试试使用另一个分割符,比如”;"。
//根据account取Cookie值
function getCookie() {
//读取Cookie
var decodedCookie = decodeURIComponent(document.cookie);
return decodedCookie;
}
//判断Cookie是否为空
function checkCookie() {
var info = getCookie();
if(info != ""){
return true;
}else{
return false;
}
checkCookie()函数是对我文章第一个函数window.οnlοad=function onLoginLoaded ()的补充。
将上述的代码敲完或者理解后,就可以加上form表单的补充代码。
比如我的代码(用红笔标的才是重要的,其他只是样式啥的不用管)
如有哪里不懂,可以评论,我会尽可能向你们解释代码。