案例一:通过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>
DOM实现表单验证

相关文章:

  • 2021-05-23
  • 2021-04-28
  • 2021-09-28
  • 2021-09-10
  • 2021-05-02
  • 2022-01-20
  • 2021-10-20
  • 2022-12-23
猜你喜欢
  • 2021-10-08
  • 2022-01-09
  • 2021-06-12
  • 2022-01-05
  • 2022-12-23
  • 2021-07-22
  • 2021-11-30
相关资源
相似解决方案