jquery - 使用 Jquery 在文本框中本地存储

标签 jquery textbox local-storage

我是 jquery 和 localstorage 的新手。我想使用 jquery 对所有文本框使用 localstorage。

<input id="in-1" type="text" />
<br />
<input id="in-2" type="text" />
<br />
<input id="in-3" type="text" />
<br />
<input id="in-4" type="text" />
<br />

我正在尝试遵循这个脚本:

(function ($) {
if (typeof (window.localStorage) != "undefined") {
    $.each($("input[type=text]"), function () {
        localStorage.getItem($(this).attr("id")));
    });
    $("input[type=text]").on("change", function () {
        localStorage.setItem($(this).attr("id"), $(this).val());

    });
}
})(jQuery);

但我无法完成这项工作。

最佳答案

您需要重新设置该值

jQuery(function ($) {
    if (typeof (window.localStorage) != "undefined") {
        //set the value to the text fields
        $("input[type=text]").val(function () {
            return localStorage.getItem(this.id);
        });
        $("input[type=text]").on("change", function () {
            localStorage.setItem(this.id, $(this).val());
        });
    }
});

演示:Fiddle

关于jquery - 使用 Jquery 在文本框中本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324035/

相关文章:

javascript - 当 "name"属性中包含 "[]"括号时,如何使用 jQuery 预选择单选组按钮?

php - 选择时文本框更改

jquery - 如何使用Jquery将个人资料图像存储在本地存储中

javascript - 带有 localStorage 的待办事项应用程序

javascript - CSS 类查找器

javascript - 在选择某些东西之前隐藏 d3.chart 的详细信息

c# - 根据文本长度调整文本框和表单大小

javascript - 如果未定义,如何将本地存储设置为 0?

jquery - 如何在调整页面大小后使图像与文本保持在一起?

c# - asp.net文本框自动填充