web-storage

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>离线存储</title>
<link rel="stylesheet" href="">
</head>
<body>
<textarea id="value_text" cols="80" rows="10"></textarea>
<input id="btn_set" value="SET" type="button"></input>
<input id="btn_get" value="GET" type="button"></input>
<script type="text/javascript">
var btnSet = document.querySelector("#btn_set");
var btnGet = document.querySelector("#btn_get");
var txtValue = document.querySelector("#value_text");
btnGet.addEventListener("click",function(){
if (window.localStorage) {//兼容性判断
// txtValue.value = localStorage.getItem("key1");//两种方法,推荐使用
txtValue.value=localStorage['key1'];
}

});
btnSet.addEventListener("click",function(){
if (window.localStorage) {
// localStorage.setItem("key1",txtValue.value);
localStorage['key1'] = txtValue.value;
}

})
</script>
</body>
</html>

localStorage:离线存储,是永久的,如果不删除永远存在,是存储在local storage里面

sessionStorage:暂时的,浏览器关闭后消失,是存储在session storage里面

txtValue.value = localStorage.getItem("key1");
txtValue.value=localStorage['key1'];

两种方法是一样的,但是如果键不存的话,localStorage.getItem返回的是"",localStorage['key1']返回的是undefined

猜你喜欢

转载自www.cnblogs.com/wyq-web/p/9420557.html