JavaScript--取消a標簽和form的submit提交默認行為


 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script>
 7         /**
 8          *    取消瀏覽器默認行為
 9          *       如:
10          *          a鏈接跳轉,
11          *          submit按鈕提交表單
12          *          (PS:右鍵彈出菜單也是)
13          *       實現方式:
14          *          event.preventDefault();
15          *          return false;
16          *
17          * */
18         window.onload = function () {
19             var link = document.getElementById('link');
20             var check = document.getElementById("check");
21             // 表單元素獲取
22             var inputTexts = document.querySelectorAll("[type='text']");
23             link.onclick = function () {
24                 //取消瀏覽器默認行為
25                 //event.preventDefault();
26                 return false;
27             }
28 
29             // 阻止右鍵彈出菜單
30             document.oncontextmenu = function () {
31                 return false;
32             }
33 
34             check.onclick = function () {
35                 event.preventDefault();
36                 if(inputTexts[0].value.indexOf('username') != -1) {
37                     console.log("登錄成功!請跳轉頁面~");
38                 }else{
39                     console.log("登錄失敗!請重新充值~");
40                 }
41             }
42 
43 
44         }
45     </script>
46 </head>
47 <body>
48 <form action="http://www.baidu.com">
49     <!-- 表單提交的時候,往往要先把數據進行驗證,所以要先把默認的提交行為取消,數據通過檢測合法后,配合JS實現數據的提交 -->
50     <input type="text" value="我是username!!" name="username">
51     <input type="submit" value="提交" id="check"/>
52 </form>
53 <a href="http://www.baidu.com">a鏈接標簽有默認行為</a>
54 <a href="#">a鏈接標簽有默認行為</a>
55 <a href="javascrit:;">a鏈接標簽有默認行為</a>
56 <a href="http://www.baidu.com" id="link">a鏈接標簽有默認行為</a>
57 </body>
58 </html>

 


免責聲明!

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



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