<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form name="f1" action="test.html" method="post">
用户名:<input type="text" name="username"><span style="color:red;">用户名必填</span><br>
<input type="submit" value="提交">
</form>
<script>
function zuzhi(e) {
if(e.preventDefault){
e.preventDefault();
}else{
e.returnValue = false;
}
}
var f1 = document.f1;
f1.onsubmit = function(evt){
if(this.username.value == ''){
alert('用户名不能为空');
var e = window.event||evt;
zuzhi(e);
}
};
document.querySelector('input[type="submit"]').onclick = function (evt) {
if(document.f1.username.value == ''){
alert('用户名不能为空');
return false;
}
};
</script>
<a href="test.html" onclick="return confirm('你确定要提交吗');">跳转</a>
</body>
</html>