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

语法

storage.setItem(keyName, keyValue);

参数

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

返回值

undefined

示例

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

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

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

规范

Specification Status Comment
Unknown
setItem()
Unknown  

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
Basic supportChrome Full support 4Edge Full support 12Firefox Full support 3.5IE Full support 8Opera Full support 10.5Safari Full support 4WebView Android Full support YesChrome Android Full support 18Edge Mobile Full support 13Firefox Android Full support 6Opera Android Full support 11Safari iOS Full support 3.2Samsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown

参见

文档标签和贡献者

标签: 
此页面的贡献者: mdnwebdocs-bot, zhangchen, AlexChao
最后编辑者: mdnwebdocs-bot,