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

瀏覽器相容性

另見