Blogger Information
Blog 26
fans 0
comment 1
visits 10522
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示禁用表单默认提交的三种方式
P粉751989631
Original
430 people have browsed it

实例演示禁用表单默认提交的三种方式

  1. <!DOCTYPE html>
  2. <html lang="zh-cn">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>表单事件</title>
  8. <link rel="stylesheet" href="form.css" />
  9. </head>
  10. <body>
  11. <form action="login.php" method="post" id="login">
  12. <label class="title">用户登录</label>
  13. <label for="email">邮箱:</label>
  14. <input type="email" id="email" name="email" value="" autofocus />
  15. <label for="password">密码:</label>
  16. <input type="password" id="password" name="password" />
  17. <button name="submit">登录</button>
  18. </form>
  19. <script>
  20. document.forms.login.submit.onclick = function (ev) {
  21. // 禁用默认提交行为
  22. ev.preventDefault();
  23. // // 禁用冒泡
  24. ev.stopPropagation();
  25. // // 因为当前不存在事件委托,不需要利用事件冒泡
  26. // // 不用再区分事件主体的类型的, 之前要区分: 绑定和触发
  27. // // 事件主体: 二合一
  28. console.log(ev.target === ev.currentTarget);
  29. console.log(this === ev.target);
  30. // * * 当前事件主体的3种形式
  31. // * * 1. ev.target
  32. // * * 2. ev.currentTarget
  33. // * * 3. this
  34. // form属性: 始终指向当前表单对象,每一个控件都有的
  35. // input,select,button,textarea...
  36. console.log(this.form);
  37. // email
  38. let email = this.form.email;
  39. // password
  40. let password = this.form.password;
  41. // 非空验证
  42. if (email.value.trim().length === 0) {
  43. alert("邮箱不能为空");
  44. email.focus();
  45. return false;
  46. } else if (password.value.trim().length === 0) {
  47. alert("密码不能为空");
  48. password.focus();
  49. return false;
  50. }
  51. // 禁用表单默认提交行为的3种方法
  52. // * * 1. form.onsubmit = 'return false'
  53. // * * 2. form.button.type = 'button'
  54. // * * 3. event.preventDefault()
  55. /**
  56. * 其它表单事件
  57. * 1. submit: 提交
  58. * 2. focus: 焦点
  59. * 3. blur: 失去焦点
  60. * 4. change: 值改变,且失去焦点时
  61. * 5. input: 值一旦改变就触发, 不等失去焦点
  62. };
  63. </script>
  64. </body>
  65. </html>

运行结果

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:总结的很好, 继续加油
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post