Javascript / jQuery localStorage API 不工作

Javascript / jQuery with localStorage API not working

我正在尝试使用 localStorage API 在用户提交表单时获取电子邮件值,然后稍后填充另一个表单字段。

我先尝试使用原版 javascript:

window.onload = function() {

  // Check for LocalStorage support.
  if (localStorage) {

    // Add an event listener for form submissions
    document.getElementById('searchBooking').addEventListener('submit', function() {
      // Get the value of the email field.
      var email = document.getElementById('email').value;

      // Save the email in localStorage.
      localStorage.setItem('email', email);
    });

  }  

  // Retrieve the users email.
   var email = localStorage.getItem('email');

   if (email != "undefined" || email != "null") {
     document.getElementById('guestEmail').innerHTML = email;
   } else {
     document.getElementById('guestEmail').innerHTML = "";
   }

}

但在第 21 行的浏览器控制台中收到此错误消息:

Uncaught TypeError: Cannot set property 'innerHTML' of null

然后我尝试了这个 jQuery:

$(function() {
  // Check for LocalStorage support.
  if (localStorage) {
    // Add an event listener for form submissions
    $('#searchBooking').on('submit', function() {
      // Get the value of the email field.
      var email = $('#email').value;
      // Save the name in localStorage.
      localStorage.setItem('#email', email);
  });
  }

  var email = localStorage.getItem('#email');
  if (email != "undefined" || email != "null") {
    $('#guestEmail').html = email;
  }
   else {
    $('#guestEmail').html = "";
    }
});

我没有收到错误消息,但没有任何效果。

抱歉,我对Javascript很陌生,不经常使用它,但我确实需要保存这个值并以另一种形式重新填充它。

在查看了您的 gist link 后,我发现 guestEmail 是您页面上的 textbox,因此innerHTML 在这里不起作用。 .value.html 的 jquery 实现也不正确。

您需要按如下方式更新您的 jquery

$(function() {
    // Check for LocalStorage support. 
    if (localStorage) {
        // Add an event listener for form submissions 

        $('form').on('submit', function() {
            // Get the value of the email field. 
            var email = $('#email').val();
            // Save the name in localStorage. 
            localStorage.setItem('#email', email);
            $('#guestEmail').html(email);
            console.log(localStorage.getItem('#email'));
        });
    }

    var emailLocalStorage = localStorage.getItem('#email');
    console.log(emailLocalStorage);

    if (typeof emailLocalStorage != "undefined" && emailLocalStorage != "null") {
        $('#guestEmail').val(emailLocalStorage);
        console.log(emailLocalStorage)
    } else {
        $('#guestEmail').val("");
    }
});

希望对您有所帮助。