使用事件的preventDefault()方法改變默認行為


事件有屬性,還有方法,還有事件。事件本身是個對象^_^

事件的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>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM