getItem()
作为 Storage
接口的方法,接受一个键名(key name)作为参数,并返回对应键名的值(key's value)。
语法
var aValue = storage.getItem(keyName);
参数
keyName
- 一个包含键名的
DOMString
。
返回值
一个 DOMString
,键名对应的值。如果键名不存在于存储中,则返回 null
。
示例
下面的函数从本地存储中获取三个数据项,然后使用他们在页面上设置自定义样式:
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; htmlElem.style.backgroundColor = '#' + currentColor; pElem.style.fontFamily = currentFont; imgElem.setAttribute('src', currentImage); }
备注:一个实际的例子 Web Storage Demo。
规范
Specification | Status | Comment |
---|---|---|
Web Storage (Second edition) getItem() |
Recommendation |
浏览器兼容性
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
localStorage | 4 | 3.5 | 8 | 10.50 | 4 |
sessionStorage | 5 | 2 | 8 | 10.50 | 4 |
Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | 2.1 | ? | 8 | 11 | iOS 3.2 |
各浏览器支持的 localStorage 和 sessionStorage 容量不同。测试页面:detailed rundown of all the storage capacities for various browsers。
Note: since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.