本文講解如何用 jquery.cookie.js 實作登入記住密碼的功能,分享給大家參考,具體如下:
需要引入的 js 有 jquery.js 和 jquery.cookie.js
<script type="text/javascript" src=" jquery-1.5.2.js"></script> <script type="text/javascript" src="jquery.cookie.js"></script>
頁面載入時,先嘗試取得 cookie 的值,若 cookie 有值,就把取到的值填進輸入框,並把「記住密碼」的核取方塊勾選起來。
jQuery(function(){ //獲取cookie的值 var username = $.cookie('username'); var password = $.cookie('password'); //將獲取的值填充入輸入框中 $('#uName').val(username); $('#psw').val(password); if(username != null && username != '' && password != null && password != ''){//選中保存秘密的復選框 $("#remember_password").attr('checked',true); } }); 登入時判斷「記住密碼」核取方塊是否勾選:若勾選則建立 cookie(有效期可自行決定,下方範例為 7 天);若未勾選則刪除 cookie(因為上次可能記住了密碼,本次取消記住時就必須刪除,才能讓下次登入時 cookie 沒有值)。
特別注意刪除 cookie 的操作:網路上很多文章用 $.cookie('username',null),但我實測並不奏效,每次重新登入後 cookie 都還在;改用 $.cookie('username','') 也會出問題,導致程式變得無法記住密碼。
//提交表單的處理函數 function Login() { var uName =$('#uName').val(); var psw = $('#psw').val(); if($('#remember_password').attr('checked') == true){//保存密碼 $.cookie('username',uName, {expires:7,path:'/'}); $.cookie('password',psw, {expires:7,path:'/'}); }else{//刪除cookie $.cookie('username', '', { expires: -1, path: '/' }); $.cookie('password', '', { expires: -1, path: '/' }); } //.... //提交表單的操作 } 登入頁面的「記住密碼」核取方塊:
<input type="checkbox" name="remember_password" id="remember_password"/> <span id="span_tip" style="margin-bottom:-2px;color:white;font-size:12px;">記住密碼 </span>
更多 jQuery 相關內容有興趣的讀者,可查看本站專題:《jQuery 的 cookie 操作技巧總結》、《jQuery 表格(table)操作技巧匯總》、《jQuery 拖拽特效與技巧總結》、《jQuery 擴充技巧總結》、《jQuery 常見經典特效匯總》、《jQuery 動畫與特效用法總結》、《jquery 選擇器用法總結》及《jQuery 常用插件及用法總結》
希望本文所述對大家的 jQuery 程式設計有所幫助。