事件有屬性,還有方法,還有事件。事件本身是個對象^_^
事件的preventDefault()方法改變默認行為,在事件發生前阻止,不讓其發生。這樣的應用場景有很多,常見表單驗證,如必填字段不能為空。
示例1,阻止鏈接
<body> <p>DOM使用preventDefault()方法,IE5~IE8使用returnValue</p> <p><a href="http://www.baidu.com/">去百度</a></p> <p><a href="http://www.baidu.com" id="gotobaidu">去百度,將被阻止</a></p> <script> var gotobaidu=document.getElementById("gotobaidu"); gotobaidu.addEventListener('click',stop,false); function stop(e) { if(e.preventDefault){ e.preventDefault(); }else{ window.event.returnValue=false; } } </script> </body>
示例2,阻止表單提交
<body> <p>DOM使用preventDefault()方法,IE5~IE8使用returnValue</p> <form id="myform" action="http://www.baidu.com/" method="get"> 用戶名:<input type="text" id="username" name="username"> <button type="submit">提交</button> </form> <script> var myform = document.getElementById('myform'); myform.addEventListener('submit', stop, false); function stop(e) { var username = document.getElementById('username'); // alert(username.value); if (username.value === '') { //要求輸入內容 alert("請輸入用戶名"); // 阻止 if (e.preventDefault) { e.preventDefault(); } else { window.event.returnValue = false; } } } </script> </body>