Persisting values in JavaScript object across browser refresh [duplicate]

巧了我就是萌 提交于 2019-11-27 19:56:16

Yes, you have two primary choices:

  1. Using a cookie. Cookies are easy to set from JavaScript, but a bit of a pain to read. You've said you're using jQuery; there's are a couple of jQuery plug-ins that make cookies a lot easier, if you search for "jquery cookie plugin" you'll find them.

  2. Using web storage, which is supported by all major browsers, even IE8. You have two choices: "Session" storage that only lasts for this "session," and "local" storage which persists until the user clears it out or the browser decides it needs that room for something else.

That second option is quite easy to use, you can store things using JSON-formatted strings (the JSON object is also supported by all major browsers):

Storing your object:

localStorage.yourObject = JSON.stringify(obj);

Retrieving your object (for instance, on page load), or a blank object if there's none stored:

obj = JSON.parse(localStorage.yourObject || "{}");

In the above, localStorage is a variabl (and underlying implementation) provided by the browser for local storage. You could use sessionStorage instead if you wanted session storage.

Here's a complete local storage example: Live Copy

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Local Storage</title>
</head>
<body>
  <label><code>Name</code> property for our object:
    <input type="text" id="txtName">
  </label>
  <script>
    (function() {
      var txtName = $("#txtName");
      var obj = JSON.parse(localStorage.yourObject || '{"Name": ""}');
      txtName.val(obj.Name);
      // This is obviously hyperactive:
      txtName.on("change keypress keyup blur paste click", function() {
        obj.Name = txtName.val();
        localStorage.yourObject = JSON.stringify(obj);
      });
    })();
  </script>
</body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!