0

我试图通过构造函数传递表单节点来验证表单。我知道使用 OO 有点过分,但这是一个请求。我有下面的代码,但是当我尝试提醒函数(表单)中文本框的值时,它们会以未定义的形式出现。

<SCRIPT LANGUAGE="JavaScript">
    function Validator(fields) {
        this.fields = fields;
    }

    Validator.prototype.validate = function (form) {
        for (var i = 0, l = this.fields.length; i < l; i++) {
            alert(this.fields[i].value);
            if (this.fields[i].value == 0) {
                alert("The field  is empty");
                return false;
            }
        }
    }

    var validator = new Validator(["username", "password"]);

    function runValidate(form) {
        validator.validate(form);
    }
</SCRIPT>
</head>

<body>
<form NAME="AbbeyRoad">
    <fieldset>
    <legend>Please login</legend>
        <div class="form-element">
            <label for="username"><span class="shortkey">U</span>sername:</label>
            <input type="text" name="username" id="username" accesskey="u">
        </div>
        <div class="form-element">
            <label for="password"><span class="shortkey">P</span>assword:</label>
            <input type="password" name="password" id="password" accesskey="p">
        </div>
        <input type="button" name="login" value="Login" id="login" onClick="runValidate(this.form)">
    </fieldset>
</form>
4

1 回答 1

1

改变:

alert(this.fields[i].value);

到:

alert(form[this.fields[i]].value);

还有这个:

if (this.fields[i].value == 0) {

到:

if (form[this.fields[i]].value == 0) {
于 2013-02-26T02:28:45.763 回答