如何使用localStorage保留我的输入

How to retain my inputs using localStorage

本文关键字:我的 输入 保留 localStorage 何使用      更新时间:2023-09-26

我想做的是当我的typedselected上我的输入,如果我刷新页面,它仍然保留值。

电流输出:http://jsfiddle.net/5kcsn/71/

脚本:

document.querySelector('#fname, #lname, #email, #reemail, #password, #gender, #bmonth, #bday, #byear').innerHTML = "";
var save = document.createElement('input,select');
document.querySelector('#fname, #lname, #email, #reemail, #password, #gender, #bmonth, #bday, #byear').appendChild(save);
if (!save.value) {
save.value = window.localStorage.getItem('value');
}
save.addEventListener('keyup', function () {
window.localStorage.setItem('value', save.value);
}, false);

document.ready之上添加以下事件处理程序,当任何字段值得到更改并在localStorage中存储值时将调用。

完整的工作演示

(填写数据并点击运行在演示页面将获得重新加载,但数据将保持不变)

$('#fname, #lname, #email, #reemail, #password, #gender, #bmonth, #bday, #byear').on("change", function () {
    localStorage.setItem($(this).attr("id"), $(this).val())
});
下面的代码将恢复localStorage在页面加载 时的值
$('#fname, #lname, #email, #reemail, #password, #gender, #bmonth, #bday, #byear').each(function (ind, val) {
    if ($(val).attr("id") != "gender") {
        $(val).val(localStorage.getItem($(val).attr("id")))
    }
    else {
        if (localStorage.getItem($(val).attr("id")) == "male")
            $("#gender[value=male]").prop("checked", true);
        else
            $("#gender[value=female]").prop("checked", true);
    }
});