日期:2014-05-16  浏览次数:20391 次

绑定Dom对象属性时候出错?
代码如下:
HTML code

<head>
    <title>Exercise</title>
</head>

<body>
    <div>
        <h2>数据校验表单</h2>
        <form method="post" name="register" action="#">
            用户名:<input type="text" name="user" /><br />
            密&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="pass" /><br />
            电&nbsp;&nbsp;&nbsp;&nbsp;邮:<input type="text" name="email" /><br />
            <input type="submit" value="提交" /><br />
        </form>
    </div>
    
    <script type="text/javascript">
        String.prototype.trim = function() {
            return this.replace(/^\s*/, "").replace(/\s*$/, "");
        }
        var check = function() {
            var form = document.forms[0];
            var errStr = "";
            if (form.user.value == null || form.user.value.trim() == "") {
                errStr += "\n用户名不能为空!";
                form.user.focus();
            }
            
            if (form.pass.value == null || form.pass.value.trim() == "") {
                errStr += "\n密码不能为空!";
                form.pass.focus();
            }
            
            if (form.email.value == null || form.email.value.trim() == "") {
                errStr += "\n电子邮件不能为空!";
                form.email.focus();
            }
            
            if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(form.email.value.trim())) {
                errStr += "\n电子邮件的格式不正确!";
                form.email.focus();
            }
            if (errStr != "") {
                alert(errStr);
                return false;
            }
        }
        document.form[0].onsubmit = check;
    </script>
</body>


用Chrome进行调试的时候,总是提示“Cannot read property '0' of undefined.”,不知道怎么回事?
这是来自《疯狂HTML5/CSS3/JavaScript讲义》上面的代码。

------解决方案--------------------
document.forms[0].onsubmit = check;