記住密碼

分享一段代碼實例,它簡單演示了localStorage的使用。

代碼實例如下:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>記住密碼</title>
</head>
<body>
用戶名<input type="text" id="ursename"> <br>
密碼  <input type="text" id="password"> <br>
<input id="chk" type="checkbox">
<lable for="chk">自動登錄</lable>
<script>
//localStorage.getItem('')獲取要存儲的值
$('#chk').click(function() {
    if (this.checked) {
      //將值存儲在本地
      localStorage.setItem('names', $("#ursename").val());
      localStorage.setItem(('pass'), $('#password').val());
      //                           alert(localStorage.getItem('names'));
      //                           alert(localStorage.getItem('pass'))
    } else {
      //在本地刪除存儲
      localStorage.removeItem('names');
      localStorage.removeItem('pass');
      // console.log(localStorage.getItem('names'))
    }
  })
  //判斷是否有存儲值如果有的話取出存儲的值
if (localStorage.getItem('names') && localStorage.getItem('pass')) {
  $('#ursename').val(localStorage.getItem('names'));
  $('#password').val(localStorage.getItem('pass'));
  $('#chk').prop("checked", true);
}
</script>
</body>
</html>
發佈了7 篇原創文章 · 獲贊 11 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章