1、local storage
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>localStorage</title>
</head>
<body>
<h1>localStorage</h1>
<button onclick="saveData()">点我保存一个数据</button>
<button onclick="readData()">点我读取一个数据</button>
<button onclick="deleteData()">点我删除一个数据</button>
<button onclick="deleteAllData()">点我清空所有数据</button>
<script type="text/javascript">
let person = {name:'张仨',age:18};
function saveData() {
localStorage.setItem('msg','hello');
localStorage.setItem('msg2',666);
localStorage.setItem('person',JSON.stringify(person));
}
function readData() {
console.log(localStorage.getItem('msg'));
console.log(localStorage.getItem('msg2'));
const result = localStorage.getItem('person');
console.log(JSON.parse(result));
}
function deleteData() {
localStorage.removeItem('msg');
localStorage.removeItem('msg2');
localStorage.removeItem('person');
}
function deleteAllData() {
localStorage.clear();
}
</script>
</body>
</html>
2、session storage
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sessionStorage</title>
</head>
<body>
<h1>localStorage</h1>
<button onclick="saveData()">点我保存一个数据</button>
<button onclick="readData()">点我读取一个数据</button>
<button onclick="deleteData()">点我删除一个数据</button>
<button onclick="deleteAllData()">点我清空所有数据</button>
<script type="text/javascript">
let person = {name:'张仨',age:18};
function saveData() {
sessionStorage.setItem('msg','hello');
sessionStorage.setItem('msg2',666);
sessionStorage.setItem('person',JSON.stringify(person));
}
function readData() {
console.log(sessionStorage.getItem('msg'));
console.log(sessionStorage.getItem('msg2'));
const result = sessionStorage.getItem('person');
console.log(JSON.parse(result));
}
function deleteData() {
sessionStorage.removeItem('msg');
sessionStorage.removeItem('msg2');
sessionStorage.removeItem('person');
}
function deleteAllData() {
localStorage.clear();
}
</script>
</body>
</html>
3、总结