2022-10-26 17:29:58
浏览数 (2)
案例分析
- 把数据存起来,用到本地存储
- 关闭页面,也可以显示用户名,所以用到localStorage
- 打开页面,先判断是否有这个用户名,如果有,就在表单里面显示用户名,并且勾选复选框
- 当复选框发生改变的时候change事件
- 如果勾选,就存储,否则就移除
案例代码
代码语言:javascript
复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="username">
<input type="checkbox" name="" id="remember">记住用户名
<script>
var usernamee = document.querySelector('#username');
var remember = document.querySelector('#remember');
if (localStorage.getItem('username')) {
username.value = localStorage.getItem('username');
remember.checked = true;
}
remember.addEventListener('change', function () {
if (this.checked) {
localStorage.setItem('username', username.value)
} else {
localStorage.removeItem('username')
}
});
</script>
</body>
</html>