温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js如何实现登录时记住密码

发布时间:2021-03-11 16:27:55 来源:亿速云 阅读:206 作者:TREX 栏目:web开发

本篇内容主要讲解“js如何实现登录时记住密码”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“js如何实现登录时记住密码”吧!

JS是什么

JS是JavaScript的简称,它是一种直译式的脚本语言,其解释器被称为JavaScript引擎,是浏览器的一部分,主要用于web的开发,可以给网站添加各种各样的动态效果,让网页更加美观。

常见的很多网站登录,都有记住密码功能,下面是用js实现的记住密码功能(代码用的源生js,不用引入任何插件,大家如果引入了jQuery,可以进行修改,优化)

js部分

window.onload = function(){
 var oForm = document.getElementById('myForm');
 var oUser = document.getElementById('username');
 var oPswd = document.getElementById('passwrod');
 var oRemember = document.getElementById('remember');
 //页面初始化时,如果帐号密码cookie存在则填充
 if (getCookie('username') && getCookie('password')) {
 oUser.value = getCookie('username');
 oPswd.value = getCookie('password');
 oRemember.checked = true;
 }
 //复选框勾选状态发生改变时,如果未勾选则清除cookie
 oRemember.onchange = function() {
 if (!this.checked) {
  delCookie('username');
  delCookie('password');
 }
 };
 //表单提交事件触发时,如果复选框是勾选状态则保存cookie
 oForm.onsubmit = function() {
 if (remember.checked) {
  setCookie('username', oUser.value, 7); //保存帐号到cookie,有效期7天
  setCookie('password', oPswd.value, 7); //保存密码到cookie,有效期7天
 }
 };
};
//设置cookie
function setCookie(name, value, day) {
 var date = new Date();
 date.setDate(date.getDate() + day);
 document.cookie = name + '=' + value + ';expires=' + date;
};
//获取cookie
function getCookie(name) {
 var reg = RegExp(name + '=([^;]+)');
 var arr = document.cookie.match(reg);
 if (arr) {
 return arr[1];
 } else {
 return '';
 }
};
//删除cookie
function delCookie(name) {
 setCookie(name, null, -1);
};

登录页面

<form id="myForm" action="login" method="post">
 <input type="text" value="" class="inp" name = "username" id="username" />
 <input type="password" value="" class="inp" name = "password" id="passwrod" />
 
 <input type="text" class="inp" id="yzm" placeholder="验证码" />
 <img id="img" src="getCode" onclick="changeImg()">
 
 <div >
 <span><input type="checkbox" id="remember"><label for="remember">记住我</label></span>
 <span >注册</span>
 </div>
 
 <button type="button" class="inp" id="btn">立即登录</button>
</form>

注意js里边的id对应:

js如何实现登录时记住密码

到此,相信大家对“js如何实现登录时记住密码”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI