js中记住密码功能

js中记住密码功能(在前端实现)

直接上例子(如果你也要实现的话注意改一些变量名称,jsp代码不包含样式

Jsp代码:

<form class="am-form tpl-form-line-form" id="loginForm"
action="<c:url value='/user_login.action'/>" method="post">
<div class="am-form-group">
<input type="text" class="tpl-form-input" name="username"
id="username" placeholder="请输入账号" autofocus>
</div>
<div class="am-form-group">
<input type="password" class="tpl-form-input" name="password"
id="password" placeholder="请输入密码">
</div>
<div class="am-form-group tpl-login-remember-me">
<input id="remember-me" type="checkbox"> <label
for="remember-me"> 记住密码 </label>
</div>
<div class="am-form-group tpl-login-remember-me">
<label for="remember-me"> 合作账号登录: </label> <a
href="http://www.qq.com/"
class="am-icon-qq am-icon-btn am-primary"></a> <a
href="https://wx.qq.com/"
class="am-icon-weixin am-icon-btn am-success"></a> <a
href="http://weibo.com/login.php"
class="am-icon-weibo am-icon-btn am-danger"></a>
</div>
<div class="am-form-group"> <button type="submit"
class="am-btn am-btn-primary am-btn-block tpl-btn-bg-color-success tpl-login-btn">登录</button> </div>
</form>

Js代码:

<script>
// 得到cookie
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_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 "";
} // 删除cookie
function delCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(name);
if (cval != null)
document.cookie = name + "=" + cval + ";expires="
+ exp.toGMTString();
} // 设置cookie
function setCookie(c_name, value, expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = c_name
+ "="
+ escape(value)
+ ((expiredays == null) ? "" : ";expires="
+ exdate.toGMTString());
} // 判断复选框是否选中
function isChecked(bool) {
if (bool) {
var password = $("#password").val();
setCookie("password", password, 10);
} else {
delCookie("password");
}
} $(function() {
// 设置复选框点击事件
$("#remember-me").click(function() {
var bool = $("#remember-me").prop("checked");
isChecked(bool);
}); /*Map<String(Cookie名称),Cookie(Cookie本身)>*/
// 获取cookie中的用户名
var username = window.decodeURI("${cookie.username.value}");
if ("${requestScope.user.username}") {
username = "${requestScope.user.username}";
}
$("#username").val(username); // 获取cookie中的密码
var password = getCookie("password");
if ("${requestScope.user.password}") {
password = "${requestScope.user.password}";
}
$("#password").val(password); // 密码框加载完毕就要判断复选框
var bool = $("#remember-me").prop("checked");
isChecked(bool);
});
</script>

参考教程:w3school的js操作cookie教程

上一篇:jave web 开发中 遇到修改不生效的几部方法 总结


下一篇:javascript-jQuery UI令牌