JavaScript中,阻止form表单自动提交的方法有两种:
(1) 使用preventDefault()
在标准浏览器中,阻止浏览器自动提交form表单的默认行为使用event.preventDefault()。
而在IE6 - 8中,使用returnValue属性来实现。
<form action="" method="post">
<input type="text" name="username" >
<input type="password" name="password" >
<input type="submit" value="Submit" id="submit" >
</form>
<script>
var btn = document.getElementById("submit");
btn .onclick = function (event) {
alert("preventDefault!");
var event = event || window.event;
event.preventDefault(); // 兼容标准浏览器
window.event.returnValue = false; // 兼容IE6 - 8
};
</script>
(2) 使用return false
使用return false同样也可以阻止form表单提交
<form action="" method="post">
<input type="text" name="username" >
<input type="password" name="password" >
<input type="submit" value="Submit" id="submit" >
</form>
<script>
var btn = document.getElementById("submit");
btn .onclick = function (event) {
alert("preventDefault!");
return false;
};
</script>