【问题标题】:jQuery: Using web storage/local storage on input fieldsjQuery:在输入字段上使用网络存储/本地存储
【发布时间】:2013-11-18 00:11:04
【问题描述】:

我正在尝试保存/检索表单中所有输入字段的值。不幸的是,这不起作用。
令人沮丧的是,我不知道出了什么问题。我已经测试了类型:键和值都是字符串。事件已正确附加,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?
  • 请放到jsfiddle中。并显示 html 内容。
  • @TusharGupta 我使用的是 jQuery 版本 1.8.3。

标签: javascript jquery html local-storage web-storage


【解决方案1】:

从 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());
 });

【讨论】:

    【解决方案2】:
    1. .live() 在 1.9 中被移除并从 1.7 中弃用
    2. 我在第一个 each 循环中没有看到任何值设置器 $(this).val(localStorage.getItem($(this).attr("id"))) 来填充值。

    【讨论】:

    • 谢谢,这解决了我的问题——我真笨!我检索了该值,但根本没有将其作为值输入!
    猜你喜欢
    • 2012-07-28
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2019-10-12
    • 1970-01-01
    • 2013-08-04
    相关资源
    最近更新 更多