在文本字段中显示保存的本地存储变量 - javascript

Displaying saved localstorage variables in a textfield - javascript

我使用 localstorage 保存了一些变量,我想做的是在每次页面加载时自动将它们放入文本字​​段

<script language="javascript">

function save() {
    var value1 = document.getElementById("email").value;
    var value2 = document.getElementById("password").value;

    localStorage.setItem("eaddress", value1);
    localStorage.setItem("pwd", value2);

}

  </script>

我在页面上有一些文本字段,即电子邮件和密码

如果您想使用 jQuery 执行此操作,这应该可以完成您想要执行的操作。请注意,我无法在下面的代码片段中获得演示 运行,因为 Stack Overflow 正在阻止表单提交。

$(function() {
  var
    $email = $('#email'),
    $password = $('#password'),
    emailValue = localStorage.getItem("eaddress"),
    passwordValue = localStorage.getItem("pwd");

  // SAVE VARIABLES TO LOCAL STORAGE
  $('form').on('submit', function() {
    localStorage.setItem("eaddress", $email.val());
    localStorage.setItem("pwd", $password.val());
  });
  
  // IF EMAIL AND PASSWORD ARE SAVED, PREPOPULATE THE FORM FIELDS
  if (emailValue != null) {
    $email.val(emailValue);
  }
  if (passwordValue != null) {
    $password.val(passwordValue);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="email" id="email" />
  <input type="password" id="password" />
  <button type="submit">Submit</button>
</form>