Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<h2 class="title" id="one">php中文网</h2>
const h2 = document.querySelector('.title');
console.log(h2.id);//获取id
console.log(h2.className);//获取class
h2.classList.add('active');
h2.classList.add('bgc');
//这样之后class的类就添加了两个变成了;
//<h2 class="title active bgc" id="one">php中文网</h2>
//判断是否有这个类,存在则返回true,不存在则返回false
console.log(h2.classList.contains('active'));
console.log(h2.classList.contains('hello'));
h2.classList.remove('bgc');
//replace(要被替换的,新的值)
h2.classList.replace('active', 'em');
//如果之前有这个样式,就去掉,没有就加上,互逆的操作
h2.classList.toggle('bgc2');
<!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="../style.css" />
</head>
<body>
<!-- 2. onsubmit="return false;" -->
<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>
function check(ele) {
// 第3种方式,禁用默认行为
event.preventDefault();
// 防止冒泡
event.stopPropagation();
// 非空验证
// 每一个表单控件input,都有一个form属性,指向所属的表单元素
console.log(ele.form);
// 通过form属性可以获取到表单中所有元素的值
// console.log(ele.form.email);
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('密码也不能为空');
email.focus();
return false;
} else {
alert('验证通过');
}
}
//当邮箱输入框失去焦点时,则检测输入框是否为空
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>