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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。