getItem()方法在给定的存储对象中,返回指定键名的值。
如果指定的键不存在,则此方法返回null。
getItem()方法属于存储对象,可以是localStorage对象或sessionStorrage对象。
localStorage.getItem(keyName)
sessionStorage.getItem(keyName)
var x = localStorage.getItem("image");测试看看‹/›表中的数字指定了完全支持getItem()方法的第一个浏览器版本:
| Method | ![]() | ![]() | ![]() | ![]() | ![]() |
| getItem() | 4 | 3.5 | 11.5 | 4 | 9 |
| 参数 | 描述 |
|---|---|
| keyName | 一个字符串,其中包含要检索其值的键的名称 |
| 返回值: | 包含指定键值的字符串。如果指定的键不存在,则返回null |
|---|---|
| DOM版本: | 网络存储API |
返回指定的会话存储项的值:
var x = sessionStorage.getItem("age");测试看看‹/›您还可以使用点表示法获取值:
var x = localStorage.url;测试看看‹/›
以下函数从本地存储中检索三个数据项,然后使用它们在页面上设置自定义样式:
function setStyles() {
var currentColor = localStorage.getItem('bgcolor');
var currentFont = localStorage.getItem('font');
var currentImage = localStorage.getItem('image');
document.getElementById('bgcolor').value = currentColor;
document.getElementById('font').value = currentFont;
document.getElementById('image').value = currentImage;
root.style.backgroundColor = currentColor;
p.style.fontFamily = currentFont;
img.setAttribute('src', currentImage);
}测试看看‹/›HTML教程:Web存储API
窗口(Window)参考:window.localStorage属性
窗口(Window)参考:window.sessionStorage属性