超簡單的localStorage實現記住密碼的功能


HTML5 提供了兩種在客戶端存儲數據的新方法:

  • localStorage - 沒有時間限制的數據存儲
  • sessionStorage - 針對一個 session 的數據存儲

之前,這些都是由 cookie 完成的。但是 cookie 不適合大量數據的存儲,因為它們由每個對服務器的請求來傳遞,這使得 cookie 速度很慢而且效率也不高。

在 HTML5 中,數據不是由每個服務器請求傳遞的,而是只有在請求時使用數據。它使在不影響網站性能的情況下存儲大量數據成為可能。

對於不同的網站,數據存儲於不同的區域,並且一個網站只能訪問其自身的數據。

HTML5 使用 JavaScript 來存儲和訪問數據。

localStorage 方法存儲的數據沒有時間限制。第二天、第二周或下一年之后,數據依然可用。

 

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title></title>
 5     <meta charset="utf-8">
 6     <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
 7 </head>
 8 <style type="text/css">
 9     form{
10         width: 300px;
11         padding: 10px 0px 20px 30px;
12         height:auto;
13         border-radius: 6px;
14         border-left:8px solid #19a049;
15         background:#eee;
16         margin:100px auto;
17     }
18     #user,#pass{
19         padding: 8px;
20         outline: none;
21         background: transparent;
22         border:1px solid #999;
23         margin-top: 5px;
24     }
25     #sub{
26         padding: 6px;
27         outline: none;
28         border:none;
29         background: #19a049;
30         color:#fff;
31         width: 150px;
32         border-radius: 6px;
33         cursor: pointer;
34     }
35 </style>
36 <body>
37     <form action="" method="" onsubmit="return loginBtn_click();">
38         <h3>Log in</h3>
39         <input type="text" name="user" placeholder="user" id="user">
40         <input type="password" name="pass" placeholder="password" id="pass">
41         <input type="checkbox" id="remember" checked><br/><br/>
42         <input type="submit" id="sub">
43     </form>
44 </body>
45 <script type="text/javascript">
46     $(document).ready(function(){
47 
48         var strName = localStorage.getItem('keyName');
49         var strPass = localStorage.getItem('keyPass');
50         if(strName){
51             $('#user').val(strName);
52         }if(strPass){
53             $('#pass').val(strPass);
54         }
55 
56     });
57 
58     function loginBtn_click(){
59             var strName = $('#user').val();
60             var strPass = $('#pass').val();
61             localStorage.setItem('keyName',strName);
62             if($('#remember').is(':checked')){
63                 localStorage.setItem('keyPass',strPass);
64             }else{
65                 localStorage.removeItem('keyPass');
66             }
67         }
68 </script>
69 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM