案例
<!DOCTYPE html>
<html lang="en">
<body>
<form action="test.html">
用户名:
<input type="text" name="username" id="username">
<br>
<input type="submit" value="提交" id="submit">
</form>
</body>
</html>
<script>
var submit = document.querySelector('#submit');
var username = document.querySelector('#username');
submit.onclick = function (e) {
// 1.提交
if (username.value == '') {
alert('用户名不能为空');
return true
}
// 2.提交
if (username.value == '') {
alert('用户名不能为空');
return // undefined
}
// 2.** 阻止提交 **
if (username.value == '') {
alert('用户名不能为空');
return false;
}
// 2.** 阻止提交 **
if (username.value == '') {
alert('用户名不能为空');
e.preventDefault();
}
};
</script>
解析
-
只有 return false; 和 e.preventDefault(); 能成功阻止表单提交;
-
直接 return , 是 将 undefined 返回出去
<form> </form>
标签有个 onsubmit 属性,决定 这个表单是否提交。
当 form 中,有个标签, 它的 id 或者 type 是 submit; 一旦它被点击,就会 激活 form 的 onsubmit 属性;然后 onsubmit 根据 return 上来的值,进行判断表单是否能提交成功。
MDN 链接(截图来源)