WEB前端-JQuery-表单验证

来源:互联网 发布:下手机电视直播软件 编辑:程序博客网 时间:2024/05/29 10:38

以下是分别以两种方式 DOM& jQuery绑定事件,并对表单内容进行简要验证的代码
可以通过js的表单验证减少与后台数据交互验证的动作,从而减少响应时间

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</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="用户名"/>                <!--<span>用户名不能为空</span>-->            </div>            <div class="item">                <input  class="c1" type="password" name="pwd" label="密码"/>                <!--<span>密码不能为空</span>-->            </div>            <!--<input type="submit" value="提交" onclick="return CheckValid();" />-->            <input type="submit" value="提交" />        </form>    </div>    <script src="jquery-1.12.4.js"></script>    <script>        /*dom绑定事件方式        function CheckValid(){            var flag = true;            $('form .c1').each(function(){                var val = $(this).val();                if(val.length<=0){                    var label = $(this).attr('name');                    var tag = document.createElement('span');                    tag.innerText = label + " cannot be empty";                    $(this).after(tag);                    flag = false;                }            });            return flag;        }*/        /*jquery 绑定方式*/        $(function(){            BindCheckValid();        });        function BindCheckValid(){            $('form input[type=submit]').click(function(){                var flag = true;                $('form .c1').each(function(){                    var val = $(this).val();                    if(val.length<=0){                        var label = $(this).attr('name');                        var tag = document.createElement('span');                        tag.innerText = label + " cannot be empty";                        $(this).after(tag);                        flag = false;                    }                });            return flag;            });        }    </script></body></html>
0 0
原创粉丝点击