停止在 JavaScript 中製作表單來重新載入頁面
假設我們要實現的目標是在使用者提交此 HTML 表單時處理客戶端上的提交事件,並在提交表單時防止瀏覽器重新載入
HTML 表單
<form name="formcontact1" action="#"> <input type='text' name='email' size="36" placeholder="Your e-mail :)"/> <input type="submit" name="submit" value="SUBMIT" onclick="ValidateEmail(document.formcontact1.email)" /> </form>
現在,最簡單最可靠的做法是在定義的頂部新增以下行來調整我們的 ValidateEmail() 函式 -
function ValidateEmail(event, inputText){ event.preventDefault(); //remaining function logic goes here }
preventDefault() 的作用是告訴瀏覽器阻止其預設行為,並讓我們在客戶端本身處理表單提交事件。
完整的 HTML 程式碼如下-
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form name="formcontact1" action="#"> <input type='text' name='email' size="36" placeholder="Your e-mail :)"/> <input type="submit" name="submit" value="SUBMIT" onclick="ValidateEmail(document.formcontact1.email)" /> </form> <script> { function ValidateEmail(event, inputText){ event.preventDefault(); //remaining function logic goes here } } </script> </body> </html>
廣告