Blogger Information
Blog 40
fans 0
comment 1
visits 34268
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
jQuery常用dom操作之验证用户名
景云
Original
483 people have browsed it

先引入库

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>

css

  1. form{
  2. display: grid;
  3. width: 20em;
  4. gap:1em;
  5. border:1px solid gray;
  6. padding: 1em;
  7. }

html

  1. <form action="check.php">
  2. 账号:<input type="text" name="username" />
  3. 密码:<input type="password" name="password" />
  4. <button>登录</button>
  5. </form>

js

  1. // 禁用表单的默认提交行为
  2. $("form").submit(ev=>ev.preventDefault());
  3. //document.querySelector("form").onsubmit=ev=>ev.preventDefault();//原生写法
  4. // 验证用户名是否为空,为空则提示不能为空,不为空验证用户名是否存在,存在则提示已存在,不存在提示可以注册
  5. const user=$("input[name='username']");
  6. //失去焦点时进行验证
  7. user.blur(function(){
  8. //不能使用箭头函数,因为箭头函数没有自己的this,它的this来自上上文
  9. // 提示信息
  10. let tips="";
  11. // 用户列表(用于测试)
  12. const users=['admin','web','jy'];
  13. //进行非空验证
  14. if($(this).val().length===0){
  15. //值得长度为0进行提示
  16. tips="用户名不能为空";
  17. $(this).focus();//激活输入框
  18. } else if(users.indexOf($(this).val())===-1){
  19. //返回-1则表示此值在用户列表中没有
  20. tips="用户名不存在,请注册"+"<button>注册</button>";
  21. }else{
  22. tips="<i style='color:green;'>用户名正确</i>";
  23. }
  24. //防止提示信息重复插入页面(判断其下一个元素的名字时不是SPAN)
  25. if($(this).next()[0].tagName!=="SPAN"){
  26. $("<span></span>").html(tips).css("color","red").insertAfter($(this));
  27. }
  28. })
  29. //用户修改文本的输入时,将提示信息清空
  30. user.on("input",function(){
  31. $(this).next("span").remove();
  32. })
Correcting teacher:天蓬老师天蓬老师

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!