html页面:
用户名 <input type="text" id="username" /><br />
密码 <input type="password" id="password" /><br />
<button id="btn">登录</button>
js代码:
<script>
//先获取用户名 密码进行存储
var uname = localStorage.getItem('username')
var upwd = localStorage.getItem('password')
//若二者不为空 则存
if (uname && upwd) {
username.value = uname
password.value = upwd
}
btn.onclick = function () {
localStorage.setItem('username', username.value)
localStorage.setItem('password', password.value)
console.log(username) //<input type="text" id="username">
//通过.value可以获取输入的值
console.log(username.value)
}
</script>
完整页面如下:
<!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" /><br />
密码 <input type="password" id="password" /><br />
<button id="btn">登录</button>
<script>
//先获取用户名 密码进行存储
var uname = localStorage.getItem('username')
var upwd = localStorage.getItem('password')
//若二者不为空 则存
if (uname && upwd) {
username.value = uname
password.value = upwd
}
btn.onclick = function () {
localStorage.setItem('username', username.value)
localStorage.setItem('password', password.value)
console.log(username) //<input type="text" id="username">
//通过.value可以获取输入的值
console.log(username.value)
}
</script>
</body>
</html>