js實現登入時記住密碼的方法分析
阿新 • • 發佈:2020-04-07
本文例項講述了js實現登入時記住密碼的方法。分享給大家供大家參考,具體如下:
常見的很多網站登入,都有記住密碼功能,下面是用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 style="margin: 10px;"> <span><input type="checkbox" id="remember"><label for="remember">記住我</label></span> <span style="float: right;">註冊</span> </div> <button type="button" class="inp" id="btn">立即登入</button> </form>
注意js裡邊的id對應:
更多關於JavaScript相關內容可檢視本站專題:《JavaScript操作DOM技巧總結》、《JavaScript頁面元素操作技巧總結》、《JavaScript事件相關操作與技巧大全》、《JavaScript查詢演算法技巧總結》、《JavaScript資料結構與演算法技巧總結》、《JavaScript遍歷演算法與技巧總結》及《JavaScript錯誤與除錯技巧總結》
希望本文所述對大家JavaScript程式設計有所幫助。