jQuery:在输入字段上使用Web存储/本地存储

jQuery: Using web storage/local storage on input fields

本文关键字:存储 Web 输入 字段 jQuery      更新时间:2023-09-26

我正在尝试保存/检索表单中所有输入字段的值。不幸的是,这是行不通的。
令人沮丧的是,我不知道出了什么问题。我已经测试了类型:键和值都是字符串。事件已正确附加,将触发console.log
你在这段代码中看到任何让你印象深刻的东西吗?为什么没有保存或检索任何值?

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

当然,我正在支持网络存储的浏览器中进行测试,每个输入都有一个 id。

从jQuery 1.7开始,.live()方法已被弃用。使用 .on() 附加事件处理程序。使用旧版本的 jQuery 的用户应优先使用 .delegate() 而不是 .live()。

(来自 JQuery 文档)

所以我的猜测是你有两个选择:

$("#myform input[type=text]").on("change", function () {
        localStorage.setItem($(this).attr("id"), $(this).val());
 });

$("#myform input[type=text]").delegate("change", function () {
        localStorage.setItem($(this).attr("id"), $(this).val());
 });
  1. .live() 在 1.9 中删除,并从 1.7 中弃用
  2. 我在第一个each循环中没有看到任何值设置器$(this).val(localStorage.getItem($(this).attr("id")))来填充值。