使用Jquery在文本框中进行本地存储

时间:2014-01-24 03:47:35

标签: 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);

但我无法做到这一点。

2 个答案:

答案 0 :(得分:4)

您需要重新设置值

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

答案 1 :(得分:0)

试试这个:

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的更多信息。