
- jQuery 教程
- jQuery - 首頁
- jQuery - 路線圖
- jQuery - 概述
- jQuery - 基礎
- jQuery - 語法
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 屬性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 新增元素
- jQuery - 刪除元素
- jQuery - 替換元素
- jQuery CSS 操作
- jQuery - CSS 類
- jQuery - 尺寸
- jQuery - CSS 屬性
- jQuery 效果
- jQuery - 效果
- jQuery - 動畫
- jQuery - 鏈式呼叫
- jQuery - 回撥函式
- jQuery 遍歷
- jQuery - 遍歷
- jQuery - 遍歷祖先元素
- jQuery - 遍歷子孫元素
- jQuery UI
- jQuery - 互動
- jQuery - 小部件
- jQuery - 主題
- jQuery 參考
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍歷
- jQuery - 其他
- jQuery - 屬性
- jQuery - 工具函式
- jQuery 外掛
- jQuery - 外掛
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用資源
- jQuery - 問答
- jQuery - 快速指南
- jQuery - 有用資源
- jQuery - 討論
jQuery 事件 preventDefault() 方法
jQuery 的事件 preventDefault() 方法用於阻止(或停止)元素的預設行為被執行。當您想阻止瀏覽器執行其預設行為時,可以使用此方法,例如,當點選提交按鈕時阻止表單提交,或者當點選連結時阻止跳轉到連結的 URL。
您可以使用另一個名為 isDefaultPrevented() 的方法來了解此方法是否曾經被呼叫(在該事件物件上)。
語法
以下是 jQuery 事件 preventDefault() 方法的語法:
event.preventDefault()
引數
此方法不接受任何引數。
返回值
此方法沒有任何返回值。
示例 1
以下是 jQuery 事件 preventDefault() 方法的基本示例:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <p>Click on the following link to redirect to another page: </p> <a href="https://tutorialspoint.tw/index.htm">TutorialsPoint</a> <span></span> <script> $('a').click(function(event){ event.preventDefault(); alert("Default behaviour is disabled"); $('span').text("The redirection will not occur because it has been prevented") $('span').css("color", "red"); }); </script> </body> </html>
輸出
以上程式顯示一個連結。當用戶點選連結時,瀏覽器螢幕上將出現一個彈出警報,表明不允許重定向到另一個頁面。
示例 2
以下是 jQuery 事件 preventDefault() 方法的另一個示例。我們使用此方法來阻止使用者提交表單時表單的提交。
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <style> form, input, button { display: block; } form input, button { padding: 10px; margin: 10px 0px; } </style> </head> <body> <form> Username: <input type="text" placeholder="Username" name="username"> Password: <input type="password" placeholder="Password"> <button type="submit">Login</button> </form> <script> $('form').submit(function(event) { event.preventDefault(); alert("Form can't be submitted"); }); </script> </body> </html>
輸出
執行上述程式後,將建立一個包含兩個輸入欄位和一個按鈕的表單,當用戶嘗試提交表單時,瀏覽器螢幕上將出現一個彈出警報,表明無法提交表單。
jquery_ref_events.htm
廣告