Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
实例代码如下:
<!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>classList对象、blur事件进行表单非空验证</title>
<link rel="stylesheet" href="css/style.css" />
<style>
.bg{
background-color:aqua;
}
.bgn{
background-color: coral;
}
</style>
</head>
<body>
<form action="" method="post" id="login">
<label class="title">用户登录</label>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email" value="" autofocus />
<label for="password">密码:</label>
<input type="password" id="password" name="password" />
<!-- 1. type="button" 来表示这是一个普通按钮,没有提交行为 -->
<button name="submit" onclick="check(this)">登录</button>
</form>
<script>
// 1. 实例演示classList对象
document.body.classList.add("bg");
document.body.classList.remove("bg");
document.body.classList.toggle("bg");
document.body.classList.replace("bg","bgn");
document.body.classList.remove("bgn");
function check(ele){
event.preventDefault();
event.stopPropagation();
let email = ele.form.email;
let password = ele.form.password;
if(email.value.length === 0){
alert("邮箱不能为空");
email.focus();
return false;
}else if(password.value.length === 0){
alert("密码不能为空");
password.focus();
return false;
}else{
return true;
}
}
// 2. 使用blur事件进行表单非空验证
document.forms.login.email.onblur = function(){
if(this.value.length === 0){
alert("邮箱不能为空");
return false;
}
};
document.forms.login.password.onblur = function(){
if(this.value.length === 0){
alert("密码不能为空");
return false;
}
};
</script>
</body>
</html>
效果图如下: