案例一:通过DOM绑定,实现基本的表单验证
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表单验证: DOM实现</title> <style> .item{ width: 250px; height: 60px; position: relative; } .item input{ width: 200px; } .item span{ position: absolute; top: 20px; left: 0px; font-size: 8px; background-color: indianred; color: white; display: inline-block; width: 200px; } </style> </head> <body> <div> <form> <div class="item"> <input class="c1" type="text" name="username" label="用户名"/> </div> <div class="item"> <input class="c1" type="password" name="pwd" label="密码"/> </div> <input type="submit" value="提交" onclick="return CheckValid();" /> <!--DOM绑定click事件 --> </form> </div> <script src="jquery-1.12.4.js"></script> <script> var flag = true; function CheckValid() { $('form .item span').remove(); $('form .c1').each(function () { var val = $(this).val(); if(val.length<=0){ var label = $(this).attr('label'); var tag = document.createElement('span') tag.innerText = label + "不能为空"; $(this).after(tag); flag = false; } }); return flag; } </script> </body> </html>