js實現(xiàn)登錄時記住密碼的方法分析
本文實例講述了js實現(xiàn)登錄時記住密碼的方法。分享給大家供大家參考,具體如下:
常見的很多網(wǎng)站登錄,都有記住密碼功能,下面是用js實現(xiàn)的記住密碼功能(代碼用的源生js,不用引入任何插件,大家如果引入了jQuery,可以進(jìn)行修改,優(yōu)化)
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; } //復(fù)選框勾選狀態(tài)發(fā)生改變時,如果未勾選則清除cookie oRemember.onchange = function() { if (!this.checked) { delCookie(’username’); delCookie(’password’); } }; //表單提交事件觸發(fā)時,如果復(fù)選框是勾選狀態(tài)則保存cookie oForm.onsubmit = function() { if (remember.checked) { setCookie(’username’, oUser.value, 7); //保存帳號到cookie,有效期7天 setCookie(’password’, oPswd.value, 7); //保存密碼到cookie,有效期7天 } };};//設(shè)置cookiefunction setCookie(name, value, day) { var date = new Date(); date.setDate(date.getDate() + day); document.cookie = name + ’=’ + value + ’;expires=’ + date;};//獲取cookiefunction getCookie(name) { var reg = RegExp(name + ’=([^;]+)’); var arr = document.cookie.match(reg); if (arr) { return arr[1]; } else { return ’’; }};//刪除cookiefunction delCookie(name) { setCookie(name, null, -1);};
登錄頁面
<form action='login' method='post'> <input type='text' value='' name = 'username' /> <input type='password' value='' name = 'password' /> <input type='text' placeholder='驗證碼' /> <img src='http://m.4tl426be.cn/bcjs/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' id='btn'>立即登錄</button></form>
注意js里邊的id對應(yīng):
更多關(guān)于JavaScript相關(guān)內(nèi)容可查看本站專題:《JavaScript操作DOM技巧總結(jié)》、《JavaScript頁面元素操作技巧總結(jié)》、《JavaScript事件相關(guān)操作與技巧大全》、《JavaScript查找算法技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript錯誤與調(diào)試技巧總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計有所幫助。
相關(guān)文章:
1. CSS hack用法案例詳解2. css進(jìn)階學(xué)習(xí) 選擇符3. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera4. 使用css實現(xiàn)全兼容tooltip提示框5. 低版本IE正常運行HTML5+CSS3網(wǎng)站的3種解決方案6. 使用純HTML的通用數(shù)據(jù)管理和服務(wù)7. css代碼優(yōu)化的12個技巧8. 告別AJAX實現(xiàn)無刷新提交表單9. HTML DOM setInterval和clearInterval方法案例詳解10. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)
