seeionStorage会话存储
<input type="text">
<button class="">存</button>
<button class="">取</button>
<button class="">删除</button>
<button class="">清空</button>
<script>
//sessionStorage 最大存储数据量为5M;
//方法: setItem:(key,value) value 必须是字符串;
//getItem(key) 取;
//removeItem(key) 删除;
//clear() 清空;
var btns = document.querySelectorAll('button');
var input = document.querySelector('input');
btns[0].addEventListener('click', function () {
console.log([1]);
sessionStorage.setItem('uname', input.value);
})
btns[1].addEventListener('click', function () {
console.log([1]);
sessionStorage.getItem('uname', input.value);
//取值打印直接调用这个方法
console.log(sessionStorage.getItem('uname', input.value))
})
btns[2].addEventListener('click', function () {
console.log([2]);
sessionStorage.removeItem('uname');
})
btns[3].addEventListener('click', function () {
console.log([3]);
sessionStorage.clear();
})
</script>
localStorage本地存储
<input type="text" id="username">
<input type="checkbox" id="remeber">记住用户名
<!-- <button class="set">存</button>
<button class="get">取</button>
<button class="remove">删除</button>
<button class="clear">清空</button> -->
<script>
//localStorage是统一域名下数据共用方法与会话存储一致
var username = document.querySelector('#username');
var remeber = document.querySelector('#remeber');
if (localStorage.getItem('username')) {
console.log(localStorage.getItem('username'));
username.value = localStorage.getItem('username');
remeber.checked = true;
}
remeber.addEventListener('change', function () {
if (this.checked) {
localStorage.setItem('username', input.value);
} else {
localStorage.removeItem('username');
}
})
</script>