(1) return false
<form name="loginForm" action="login.aspx" method="post"> <button type="submit" value="Submit" id="submit">Submit</button> </form> <script> var submitBtn = document.getElementById("submit"); submitBtn.onclick = function (event) { alert("preventDefault!"); return false; }; </script>
(2) 使用preventDefault()
在标准浏览器中,阻止浏览器默认行为使用event.preventDefault()
,而在IE6~8中,使用returnValue
属性来实现。
<form name="loginForm" action="login.aspx" method="post"> <button type="submit" value="Submit" id="submit">Submit</button> </form> <script> var submitBtn = document.getElementById("submit"); submitBtn.onclick = function (event) { alert("preventDefault!"); var event = event || window.event; event.preventDefault(); // 兼容标准浏览器 window.event.returnValue = false; // 兼容IE6~8 };