Storage:getItem() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨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

浏览器兼容性

另见