JSP页面:
<table>
<tr>
<td>
<div>
<input id="UserID" class="text" type="text" tabindex="1"
placeholder="账号" />
</div></td>
</tr>
<tr>
<td>
<div>
<input id="password" class="text" type="password"
placeholder="密码" tabindex="2" />
</div></td>
</tr>
</table>
Js方法:
页面加载完成后执行,从Cookie中获取值,需要引入jquery.js
var cookieValue = "";
var search = "user=";
$(document).ready(function() {
setTimeout(‘setvalue()‘,1000) //1秒=1000,这里是3秒
});
function setvalue(){
if(document.cookie.length > 0) {
offset = document.cookie.indexOf(search);
if(offset != -1){
offset += search.length;
end = document.cookie.indexOf(";",offset);
if (end == -1)
end = document.cookie.length;
//获取cookies里面的值
cookieValue = unescape(document.cookie.substring(offset,end))
if(cookieValue != null){
var str = cookieValue.split("/");
document.getElementById("UserID").value= str[0];
document.getElementById("password").value = str[1];
}
}
}
}
进行登录操作时,存储信息到Cookie中
//UserID,Password为用户名密码
function SetCookie(UserID,Password)//两个参数,一个是cookie的名子,一个是值
{
var name = UserID;
var password = Password;
var Days = 7; //此 cookie 将被保存 7 天
var exp = new Date(); //生成一个现在的日期,加上保存期限,然后设置cookie的生存期限!
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = "user="+ escape(name) + "/" + escape(password) + ";expires=" + exp.toGMTString();
}
//取cookies函数--正则表达式(不会,学习正则表达式)
function getCookie(name)
{
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr != null) return unescape(arr[2]);
return null;
}
删除Cookie
function delCookie()
{
var name = "admin";
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}