We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

setItem() 作为 Storage 接口的方法,接受一个键名和值作为参数,将会把键名添加到存储中,如果键名已存在,则更新其对应的值。

语法

storage.setItem(keyName, keyValue);

参数

keyName
一个 DOMString,要创建或更新的键名。
keyValue
一个 DOMString,要创建或更新的键名对应的值。

返回值

无。

示例

下面的函数在本地存储中创建三个数据项(data items)。

function populateStorage() {
  localStorage.setItem('bgcolor', 'red');
  localStorage.setItem('font', 'Helvetica');
  localStorage.setItem('image', 'myCat.png');
}

备注:一个实际的例子 Web Storage Demo

规范

Specification Status Comment
Unknown
setItem()
Unknown  

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

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.

相关链接

使用 Web Storage API

文档标签和贡献者

此页面的贡献者: AlexChao
最后编辑者: AlexChao,