首先是html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<form id="form">
<div>
用户名 <input id= "name"type="text" >
</div>
<span></span>
<div>
密码 <input id="pwd" type="password">
</div>
<input type="submit" value="登录">
</form>
</div>
<script src="js/login.js"></script>
</body>
</html>
需要注意的是script的格式(src在尖括号<>里面),以及位置在body最下面,因为js调用了addEventListener方法,如果放在body最上面,会报错uncaught (in promise): TypeError: Cannot read property 'addEventListen
然后是对应的js代码
const name = document.getElementById('name');
const form = document.getElementById('form');
form.addEventListener('submit', e => {
e.preventDefault()
const username = name.value.trim();
if(username === '') {
alert("null name");
}
});
最后的结果如图: