Storage - Web APIs 编辑

The Storage interface of the Web Storage API provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items.

To manipulate, for instance, the session storage for a domain, a call to Window.sessionStorage is made; whereas for local storage the call is made to Window.localStorage.

Properties

Storage.length Read only
Returns an integer representing the number of data items stored in the Storage object.

Methods

Storage.key()
When passed a number n, this method will return the name of the nth key in the storage.
Storage.getItem()
When passed a key name, will return that key's value.
Storage.setItem()
When passed a key name and value, will add that key to the storage, or update that key's value if it already exists.
Storage.removeItem()
When passed a key name, will remove that key from the storage.
Storage.clear()
When invoked, will empty all keys out of the storage.

Examples

Here we access a Storage object by calling localStorage. We first test whether the local storage contains data items using !localStorage.getItem('bgcolor'). If it does, we run a function called setStyles() that grabs the data items using Storage.getItem() and uses those values to update page styles. If it doesn't, we run another function, populateStorage(), which uses Storage.setItem() to set the item values, then runs setStyles().

if(!localStorage.getItem('bgcolor')) {
  populateStorage();
} else {
  setStyles();
}

function populateStorage() {
  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
  localStorage.setItem('font', document.getElementById('font').value);
  localStorage.setItem('image', document.getElementById('image').value);

  setStyles();
}

function setStyles() {
  var currentColor = localStorage.getItem('bgcolor');
  var currentFont = localStorage.getItem('font');
  var currentImage = localStorage.getItem('image');

  document.getElementById('bgcolor').value = currentColor;
  document.getElementById('font').value = currentFont;
  document.getElementById('image').value = currentImage;

  htmlElem.style.backgroundColor = '#' + currentColor;
  pElem.style.fontFamily = currentFont;
  imgElem.setAttribute('src', currentImage);
}

Note: To see this running as a complete working example, see our Web Storage Demo.

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'Storage' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:125 次

字数:5190

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文