Storage: phương thức getItem()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Phương thức getItem() của giao diện Storage, khi được truyền vào tên khóa, sẽ trả về giá trị của khóa đó, hoặc null nếu khóa không tồn tại, trong đối tượng Storage đã cho.
Cú pháp
js
getItem(keyName)
Tham số
keyName-
Một chuỗi chứa tên của khóa mà bạn muốn truy xuất giá trị.
Giá trị trả về
Một chuỗi chứa giá trị của khóa. Nếu khóa không tồn tại, phương thức sẽ trả về null.
Ví dụ
Hàm sau lấy ba mục dữ liệu từ local storage, rồi dùng chúng để đặt kiểu tùy chỉnh cho trang.
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);
}
Note: Để xem cách dùng trong ví dụ thực tế, hãy xem Web Storage Demo.
Thông số kỹ thuật
| Specification |
|---|
| HTML> # dom-storage-getitem-dev> |