HTML DOM窗口的localStorage属性允许您使用对象在Web浏览器中存储值对。这是一个只读属性。即使关闭浏览器,该对象也不会过期。因此,数据永远不会丢失。
用法:
window.localStorage
-
使用以下命令将数据保存到localStorage:
localStorage.setItem("key", "value");
-
使用以下命令从localStorage读取数据:
var name = localStorage.getItem("key");
-
使用以下方法从localStorage中删除数据:
localStorage.removeItem("key");
示例1:保存,读取和删除数据到localStorage
<!DOCTYPE html>
<html>
<head>
<title>
HTML | DOM Window localStorage Properties
</title>
<script>
//saving data locally
function save() {
var fieldValue =
document.getElementById('textfield').value;
localStorage.setItem('text', fieldValue);
}
//reading data
function get() {
var storedValue = localStorage.getItem('text');
if (storedValue) {
document.getElementById(
'textfield').value = storedValue;
}
}
//removing stored data
function remove() {
document.getElementById(
'textfield').value = '';
localStorage.removeItem('text');
}
</script>
</head>
<body onload="get()">
<p1>
Type something in the text field and It
will Get stored locally by Browser
</p1>
<input type="text" id="textfield" />
<input type="button" value="save" onclick="save()" />
<input type="button" value="clear" onclick="remove()" />
<p2>
when you reopen or reload this page,your text
is still there.
</p2>
<p3>
<br>click on clear to remove it.</p3>
</body>
</html>
输出:
- 保存数据之前:
- 保存数据后:
- 谷歌浏览器
- IE浏览器
- Firefox
- Opera
- Safari
示例2:检查存储类型并保存数据。
<!DOCTYPE html>
<html>
<head>
<title>
HTML | DOM Window localStorage Properties
</title>
</head>
<body>
<div id="SHOW"></div>
<script>
if (typeof(Storage) !==
"undefined") {
localStorage.setItem("name",
"GEEKSFORGEEKS");
document.getElementById(
"SHOW").innerHTML =
localStorage.getItem("name");
} else {
document.getElementById(
"SHOW").innerHTML =
"YOUR BROWSER DOES NOT" +
"SUPPORT LOCALSTORAGE PROPERTY";
}
</script>
</body>
</html>
输出:
支持的浏览器:下面列出了DOM Window localStorage支持的浏览器:
相关用法
- HTML Window frames用法及代码示例
- HTML Window opener用法及代码示例
- HTML Window frameElement用法及代码示例
- HTML Window defaultStatus用法及代码示例
- HTML Window name用法及代码示例
- HTML Window self()用法及代码示例
- HTML Window top()用法及代码示例
- HTML Window status用法及代码示例
- HTML Window alert()用法及代码示例
- HTML Window atob()用法及代码示例
- HTML Window scrollBy()用法及代码示例
- HTML DOM Window btoa()用法及代码示例
- HTML Window closed用法及代码示例
注:本文由纯净天空筛选整理自AkshayGulati大神的英文原创作品 HTML | DOM Window localStorage Properties。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。