我试图让一个简单的表单页面具有一些本地存储功能,以便在页面关闭/重新加载后恢复设置/输入。
我试图开始,但我仍然在学习,所以有错误,我无法让它发挥作用。
input
字段进行了更改,则应使用新名称更新localstorage。$(document).ready(function () {
$.each($("select"), function (index, value)) {
localStorage.getItem($(this).attr(“id”));
};
});
$("select").on("change", function () {
localStorage.setItem($(this).attr(“id”), $(this));
});
我还没有设法从名称输入字段或清除功能开始,因为我甚至无法让第一个工作。
我宁愿不使用外部库,因为它会变得如此复杂,没有别的需要。
答案 0 :(得分:1)
以下内容适合您:
<强>的jQuery 强>
$('.useLocalSelect').change(function () {
var key = $(this).attr('id');
var value = $(this).val();
localStorage.setItem(key, value)
});
// use a timer for text fields and the like so that localsotrage is set 2 seconds after the user stops typing instead of after each keystroke
var t = '';
$('.useLocalInput').keyup(function () {
clearTimeout(t);
var key = $(this).attr('id');
var value = $(this).val();
t = setTimeout(function () {
localStorage.setItem(key, value)
}, 2000);
});
$('.useLocal').each(function () {
var key = $(this).attr('id');
if (localStorage.getItem(key)) {
$(this).val(localStorage.getItem(key));
}
});
$('.clearLocalSelect').click(function () {
$('.useLocalSelect').each(function () {
$(this).val('');
var key = $(this).attr('id');
localStorage.removeItem(key);
});
});
<强> HTML 强>
<label style="color: #01ACEE; font: bold 14px Tahoma;">Input
<input class="useLocal useLocalInput" id="testInput" size="40" type="text" name="website" value="" required/>
</label>
<br/>
<br/>
<label style="color: #01ACEE; font: bold 14px Tahoma;">Select</label>
<select class="useLocal useLocalSelect" id="testSelect" name="start_date">
<option value="">Select one...</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">Noember</option>
<option value="December">December</option>
</select>
<br/>
<br/>
<input type="button" class="clearLocalSelect" value="Clear Selects"/>