【问题标题】:Local storage in textboxes using Jquery使用 Jquery 在文本框中进行本地存储
【发布时间】:2014-02-14 22:29:46
【问题描述】:

我是 jquery 和 localstorage 的新手。我想使用本地存储到所有使用 jquery 的文本框。

<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 textbox local-storage


    【解决方案1】:

    试试这个:

    jQuery(function ($) {
        if (typeof (window.localStorage) != "undefined") {
    
            // will get value of specific id from the browser localStorage and set to the input 
            $("input[type=text]").val(function () {
                return localStorage.getItem(this.id);
            });
    
            // will set values in browser localStorage for further reference
            $("input[type=text]").on("change", function () {
                localStorage.setItem(this.id, $(this).val());
            });
        }
    });
    

    这是一个有效的Demo

    详情:

    在现代浏览器中使用本地存储非常简单。您所要做的就是在 JavaScript 中修改localStorage object。你可以直接这样做,或者(这可能更干净)使用 setItem()getItem() 方法:

    localStorage.setItem('favoriteflavor','vanilla');
    

    如果你读出了最喜欢的风味键,你会得到“香草”:

    var taste = localStorage.getItem('favoriteflavor');
    // -> "vanilla"
    

    删除该项目,您可以使用 - 您猜到了吗? — removeItem() 方法:

    localStorage.removeItem('favoriteflavor');
    var taste = localStorage.getItem('favoriteflavor');
    // -> null
    

    就是这样!如果您希望仅在浏览器窗口关闭之前保留数据,您也可以使用 sessionStorage 而不是 localStorage

    完整的reference here。它应该能让你更多地了解localStorage

    【讨论】:

      【解决方案2】:

      你需要重新设置值

      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

      【讨论】:

      • 还有一点,onblur 和 onchange 有什么区别?
      • @user3230425 onblur 将在每次失去焦点时触发.. 但更改只会触发输入中的值发生更改 - 您只需要使用更改事件
      猜你喜欢
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 2016-02-09
      • 2017-09-27
      • 2020-11-03
      • 2011-02-07
      相关资源
      最近更新 更多