此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Storage.getItem()

基线 广泛可用

自 2015年7月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

Storage 接口的 getItem() 方法,当传递一个键名时,将返回该键的值;而如果在给定的 Storage 对象中不存在该键,则返回 null

语法

js
getItem(keyName)

参数

keyName

一个包含你要检索的键名字符串。

返回值

一个包含键值的字符串。如果该键名不存在,则返回 null

示例

下面的函数从本地存储中获取三个数据项,然后使用他们在页面上设置自定义样式:

js
function setStyles() {
  const currentColor = localStorage.getItem("bgcolor");
  const currentFont = localStorage.getItem("font");
  const 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);
}

备注:有关实际运行的例子,详见 Web Storage 演示

规范

规范
HTML
# dom-storage-getitem-dev

浏览器兼容性

相关链接

使用 Web Storage API