javascript 阻止事件的預設行為

來源:互聯網
上載者:User
在做前端開發時,我們經常會使用到阻止事件的預設行為,以下是阻止瀏覽器預設行為的方法,
有一下兩種
1、event.preventDefault()
在非IE瀏覽器中使用,preventDefault()(取消事件的預設動作)方法來阻止事件相關聯的的預設行為。
該方法將通知 網頁瀏覽器不要執行與事件關聯的預設動作(如果存在這樣的動作)。
例如,如果 type 屬性是 "submit",在事件傳播的任意階段可以調用任意的事件控制代碼,
通過調用該方法,可以阻止提交表單。注意,如果 Event 對象的 cancelable 屬性是 fasle,
那麼就沒有預設動作,或者不能阻止預設動作。無論哪種情況,調用該方法都沒有作用。
2、window.event.returnValue = false;

在IE瀏覽器中,則使用window.event.returnValue = false;

代碼如下:

<span style="font-family:Comic Sans MS;"><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title>    <script src="scripts/jquery-2.1.0.js"></script>    <script type="text/javascript">        $(function () {            $("a").click(function (e) {                if (e && e.preventDefault)                    //阻止預設瀏覽器動作(W3C)                     e.preventDefault();                else                    //IE中阻止函數器預設動作的方式                     window.event.returnValue = false;                return false;            });        });    </script>    </head><body>    <a href="http://www.baidu.com">百度</a>   </body></html></span>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.