[英]HTML5 sessionStorage not working as expected
我正在使用 HTML5 sessionStorage 来帮助在刷新时填充表单字段,但我遇到了一些奇怪的错误。 基本上,如果我更改任何值,表单将停止工作。
我目前所写的表格在这里; http://jsfiddle.net/takuhii/rjsjj9by/1/
HTML:
<form id="storeFields" method="post" action="">
<label>First Name:</label>
<input type="text" name="firstname" id="firstName" class="form-control" value="" />
<label>Last Name:</label>
<input type="text" name="lastname" id="lastName" class="form-control" value="" />
<label>Email:</label>
<input type="email" name="email" id="email" class="form-control" value="" />
<input type="submit" class="demo-button" value="Submit" />
</form>
爪哇脚本:
function storeDetails() {
if (sessionStorage["firstname"]) {
$('#firstName').val(sessionStorage["firstname"]);
}
if (sessionStorage["lastname"]) {
$('#lastName').val(sessionStorage["lastname"]);
}
if (sessionStorage["email"]) {
$('#email').val(sessionStorage["email"]);
}
}
storeDetails();
$('.form-control').change(function () {
sessionStorage[$(this).attr('firstName')] = $(this).val();
sessionStorage[$(this).attr('lastName')] = $(this).val();
sessionStorage[$(this).attr('email')] = $(this).val();
});
$('#storeFields').submit(function() {
sessionStorage.clear();
});
我从中得出的形式是here; http://jsfiddle.net/takuhii/45zfpfru/8/
HTML:
<form id="storeFields" method="post" action="">
<label>Name:</label>
<input type="text" name="name" id="name" class="stored" value="" />
<label>Email:</label>
<input type="email" name="email" id="email" class="stored" value="" />
<label>Message:</label>
<textarea name="message" id="message" class="stored"></textarea>
<input type="submit" class="demo-button" value="Submit" />
</form>
JAVASCRIPT;
function storeDetails() {
if (localStorage["name"]) {
$('#name').val(localStorage["name"]);
}
if (localStorage["email"]) {
$('#email').val(localStorage["email"]);
}
if (localStorage["message"]) {
$('#message').val(localStorage["message"]);
}
}
storeDetails();
$('.stored').keyup(function () {
localStorage[$(this).attr('name')] = $(this).val();
});
$('#storeFields').submit(function() {
localStorage.clear();
});
我不明白的是如何简单地改变它寻找的变量,打破整个形式?
任何帮助将不胜感激,因为我真的看不出有什么问题
如果这是另一个问题的重复,我提前道歉,因为我试图寻找,但找不到满意的答案......干杯达伦
在你的 JS 中试试这个:
$('.form-control').change(function () {
sessionStorage[$(this).attr('id')] = $(this).val();
});
您希望使用 id 属性的值(firstName、LastName、email)作为设置正确会话值的键。 在您的代码中,您正在寻找不存在的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.