Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:整体效果不错, 非空验证时应是密码不能为空
<!DOCTYPE html>
<html lang="zh-CN">
<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>表单事件</title>
<link rel="stylesheet" href="form.css">
</head>
<body>
<!-- 通过onsubmit="return false"禁用提交 -->
<!-- <form action="login.php" method="post" id="login" onsubmit="return false"> -->
<form action="login.php" 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" />
<!-- form中的button,默认type="submit",改成type="button"就可以禁用 -->
<!-- <button name="submit" type="button">登录</button> -->
<!-- 禁用表单默认提交行为的3种方法
1. form.onsubmit = 'return false'
2. form.button.type = 'button'
3. event.preventDefault() -->
<button name="submit">登录</button>
</form>
<script>
// 事件对象来控制
document.forms.login.submit.onclick = function (ev) {
// 禁止默认提交行为
ev.preventDefault();
// 区分绑定和触发,事件主体二合一
console.log(ev.target === ev.currenTarget);
console.log(this === ev.target);
// 当前事件主体的三种形式
// 1. ev.target
// 2. ev.currentTarget
// 3. this
console.log(this.form);
// 非空验证
if (email.value.trim().length === 0) {
// trim过滤空的字符串
alert('账号不能为空');
email.focus();
return false;
} else if (password.value.trim().length === 0) {
alert('邮箱不能为空');
password.focus();
return false;
}
};
</script>
</body>
</html>