1. 程式人生 > >HTML5記住賬號和密碼

HTML5記住賬號和密碼

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>

  賬號:<input type="text" id="user"> 密碼:
  <input type="password" id="pwd"> 記住密碼:
  <input type="checkbox" id="remember">
  <button onclick="fn()">登入</button>

  <script type="text/javascript">
    var user = document.getElementById('user'),
      pass = document.getElementById('pwd'),
      check = document.getElementById('remember'),
      localUser = localStorage.getItem('user') || ''; //獲取到user的值並儲存
      localPass = localStorage.getItem('pass') || ''; //獲取到pwd的值並儲存
      user.value = localUser;
      pass.value = localPass;
      if (localUser !== '' && localPass !== '') {
        check.setAttribute('checked', '');
      }

    function fn() {
      if (check.checked) {
        localStorage.setItem('user', user.value);
        localStorage.setItem('pass', pass.value);
      } else {
        localStorage.setItem('user', '');
        localStorage.setItem('pass', '');
      }
    }
  </script>

</body>

</html>