1.表单验证
绑定的事件还没触发,就已经执行过了, 按钮还没按下,就已经显示span内容了
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .item{ 8 width: 250px; 9 height: 60px; 10 position: relative; 11 } 12 .item input{ 13 width: 200px; 14 } 15 .item span{ 16 position: absolute; 17 top: 20px; 18 left: 20px; 19 font-size: 8px; 20 opacity: 0.8; 21 } 22 </style> 23 </head> 24 <body> 25 <div> 26 <form> 27 <div class="item"> 28 <input type="text" name="username" label="用户名"> 29 <!-- <span>用户名不能为空</span>--> 30 </div> 31 <div class="item"> 32 <input type="password" name="pwd" label="密码"> 33 <!-- <span>密码不能为空</span>--> 34 </div> 35 <input type="submit" value="提交" > 36 </form> 37 </div> 38 <script src="jquery-3.5.0.js"></script> 39 <script> 40 $(function () { 41 BindCheck(); 42 }); 43 function BindCheck() { 44 $('form input').click(function () { 45 $('form .item span').remove(); 46 var flag=true; 47 $('form .item input[type="text"],.item input[type="password"]').each(function () { 48 // ($(this).parent().find('span')).remove(); 49 var val=$(this).val(); 50 51 if(val.length<=0){ 52 var label = $(this).attr('label'); 53 var tag=document.createElement('span'); 54 tag.innerText=label+'不能为空'; 55 $(this).after(tag); 56 flag=false; 57 } 58 }); 59 return flag; 60 }); 61 62 } 63 64 65 </script> 66 </body> 67 </html>