1)需求
//1 如果本地有用户名 就让它显示在文本框中 复选框处于勾选状态
//2 如果客户点击了 不记住用户名 我们就删除掉
2)代码实现
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <input id="username" type="text"> <input id="remember" type="checkbox">记住用户名 <script> var username = document.querySelector('#username'); var remember = document.querySelector('#remember'); //1 判断本地是否存在用户名 if (localStorage.getItem('username')) { username.value = localStorage.getItem('username'); remember.checked = true; } //2 如果用户点击了 复选框 做出对应的操作 remember.onchange = function(){ if (this.checked) { localStorage.setItem('username',username.value); } else { localStorage.removeItem('username'); } }; </script> </body> </html>