博客列表 >classList对象、blur事件进行表单非空验证

classList对象、blur事件进行表单非空验证

Blackeye
Blackeye原创
2022年04月07日 18:41:35336浏览

hw

  1. <!DOCTYPE html>
  2. <html lang="en">
  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>classList对象、blur事件进行表单非空验证</title>
  8. <link rel="stylesheet" href="style.css" />
  9. <style>
  10. .bg{
  11. background-color: aqua;
  12. }
  13. .bgn{
  14. background-color: coral;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <form action="" method="post" id="login">
  20. <label class="title">用户登录</label>
  21. <label for="email">邮箱:</label>
  22. <input type="email" id="email" name="email" value="" autofocus />
  23. <label for="password">密码:</label>
  24. <input type="password" id="password" name="password" />
  25. <!-- 1. type="button" 来表示这是一个普通按钮,没有提交行为 -->
  26. <button name="submit" onclick="check(this)">登录</button>
  27. </form>
  28. <script>
  29. // 1. 实例演示classList对象
  30. document.body.classList.add("bg");
  31. document.body.classList.remove("bg");
  32. document.body.classList.toggle("bg");
  33. document.body.classList.replace("bg","bgn");
  34. document.body.classList.remove("bgn");
  35. function check(ele){
  36. event.preventDefault();
  37. event.stopPropagation();
  38. let email = ele.form.email;
  39. let password = ele.form.password;
  40. if(email.value.length === 0){
  41. alert("邮箱不能为空");
  42. email.focus();
  43. return false;
  44. }else if(password.value.length === 0){
  45. alert("密码不能为空");
  46. password.focus();
  47. return false;
  48. }else{
  49. return true;
  50. }
  51. }
  52. // 2. 使用blur事件进行表单非空验证
  53. document.forms.login.email.onblur = function(){
  54. if(this.value.length === 0){
  55. alert("邮箱不能为空");
  56. return false;
  57. }
  58. };
  59. document.forms.login.password.onblur = function(){
  60. if(this.value.length === 0){
  61. alert("密码不能为空");
  62. return false;
  63. }
  64. };
  65. </script>
  66. </body>
  67. </html>
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议