gpt4 book ai didi

带有 localStorage API 的 Javascript/jQuery 不工作

转载 作者:行者123 更新时间:2023-11-29 21:44:23 25 4
gpt4 key购买 nike

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

我先尝试使用 vanilla 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 行的浏览器控制台中收到此错误消息:

未捕获的 TypeError:无法设置 null 的属性“innerHTML”

然后我尝试使用这个 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 链接,我发现 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("");
}
});

希望这对您有所帮助。

关于带有 localStorage API 的 Javascript/jQuery 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31706060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com