語法
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 |
瀏覽器相容性
載入中…