记住用户名案例(localStroage本地存储)
2021-08-10 本文已影响0人
圆滚滚大煤球
html+js
<input type="text" name="" id="username"><input type="checkbox" name="" id="remember">记住用户名
<script>
var username = document.querySelector('#username');
var remember = document.querySelector('#remember');
//先getusername的数据,有则存为 username.value checked打钩
if(localStorage.getItem('username')) {
username.value = localStorage.getItem('username');
remember.checked = true;
};
// 当remember状态改变时,true:把username.value存为本地数据;
// false:移除username数据;
remember.addEventListener('change',function(){
if(this.checked) {
localStorage.setItem('username',username.value);
} else {
localStorage.removeItem('username');
}
})