localStorage應用程式碼例項

antzone發表於2017-04-17

分享一段程式碼例項,它簡單演示了localStorage的使用。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
</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>

相關文章