1. 存储计数器的值

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="div1">0</div><br>
<input id="btn" value="计数" type="button"> <script>
window.onload = function(){
var div = document.getElementById("div1");
var btn = document.getElementById("btn");
var num = localStorage.getItem("num") ? localStorage.getItem("num") : 0;
div.innerHTML = num +"";
btn.onclick = function(){
num ++;
localStorage.setItem("num",num);
div.innerHTML = localStorage.getItem("num") +"";
}
}
</script>
</body>
</html>

1.2 简化

<script>
window.onload = function(){
var div = document.getElementById("div1");
var btn = document.getElementById("btn");
var num = localStorage.getItem("num") || 0;
div.innerHTML = num;
btn.onclick = function(){
num++;
div.innerHTML = num;
localStorage.setItem("num",num);
}
}
</script>

2. 校验用户名和密码

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
账号:<input type="text" id="account"><br>
密码:<input type="text" id="pwd"><br>
<input type="button" id="btn" value="登录">
<p id="info"></p>
<br><br><br><br><br><br><br><br><br><br><br> <script>
window.onload = function(){
var account = document.getElementById("account");
var pwd = document.getElementById("pwd");
var login = document.getElementById("btn");
var info = document.getElementById("info"); //展示结果用, 登录成功或登录失败!
var user = [ // 存入数据库的数据(模拟)
{'account': 'liuting', 'pwd': '123'},
{'account': 'zhangsan', 'pwd': '456'},
{'account': 'lisi', 'pwd': '789'},
{'account': 'wangwu', 'pwd': 'jqk'},
{'account': 'wanger', 'pwd': 'abc'},
{'account': 'mazi', 'pwd': 'abc123'}
]; //1. 保存数据到数据库 并从数据库中获取用户信息
var index = 0; // 保证存入的key的唯一性
var arrUser = []; //获取所有本地用户
for(var i = 0, len = user.length; i < len; i++){ //把所有的模拟的用户保存到数据库并 从数据库获取所有的用户信息
localStorage.setItem('account'+ index, user[i]['account']);
localStorage.setItem('pwd'+ index, user[i]['pwd']);
var userSave = {};
userSave['account'] = localStorage.getItem('account'+ index);
userSave['pwd'] = localStorage.getItem('pwd'+ index);
arrUser[index] = userSave;
index++;
} //2. 点击登录按钮的时候 进行账号和密码校验
login.onclick = function(){
if(arrUser){
for(var i = 0, len = arrUser.length; i < len; i++) {
//如果前台输入的账号和密码与数据库中的账号和密码一致则登录成功!反之失败!
if(account.value == arrUser[i]['account'] && pwd.value == arrUser[i]['pwd']) {
info.style.color = 'green';
info.innerHTML = "登录成功!"
return; // 跳转到首页
}else {
info.style.color = 'red';
info.innerHTML = "账号或密码有误!请重新输入!"
}
}
}else {
info.style.color = 'red';
info.innerHTML = "数据库中没有数据";
}
}
}
</script>
</body>
</html>
04-30 03:24