【问题标题】:JQuery $().each exiting too earlyJQuery $().each 过早退出
【发布时间】:2018-08-22 11:27:42
【问题描述】:

我正在使用下面的函数来验证 Web 表单上的多个输入字段。该函数使用 jQuery .each() 迭代遍历字段。 ValidateInput 函数验证每个单独的输入字段,返回真或假。

function ValidateForm() {
    var result = true;
    $('[data-regex]').each(function() {
        result = result && ValidateInput(this);
        // return true;
    });

    if ( result == false ) {
        $(".alert").show();
    }

    return result;
}

我遇到的问题是.each() 会提前终止,只要任何单个输入字段验证失败。我知道如果function() 返回false,.each() 将终止,但我不知道我是如何做到的。我什至尝试添加一个显式的return true; 作为function() 的最后一行,但这并没有什么区别。

为了完整起见,这里是ValidateInput:

function ValidateInput(thisInput) {
    var fieldName = $(thisInput).attr('name');
    var fieldValue = $(thisInput).val();
    var regex = $(thisInput).attr('data-regex');
    console.log('validating field "' + fieldName + '" value "' + fieldValue + '" with regEx "' + regex + '"';
    var re = new RegExp(regex);
    var result = re.test(fieldValue);
    if ( result ) {
        console.log('- passed');
        $(thisInput.closest(".form-group")).addClass("has-success").addClass("has-feedback")
    } else {
        console.log('- failed');
        $(thisInput.closest(".form-group")).addClass("has-error").addClass("has-feedback")
    };

    return result;
}

调用ValidateForm的代码如下:

<input type="submit" name="ct108" value="Save User" onclick="return ValidateForm();" />

我错过了什么?

【问题讨论】:

    标签: javascript jquery validation each


    【解决方案1】:

    您的 ValidateInput 方法在第一个未通过验证的方法之后停止处理,因为这行:

    result = result && ValidateInput(this);
    

    &amp;&amp; 的工作方式是,如果左边的 item 为真,则将右边的值作为值返回,否则将左边的值作为值返回。

    你可以保证每一个都是通过翻转来处理的:

    result = ValidateInput(this) && result;
    

    【讨论】:

    • 谢谢 - 这似乎已经成功了,但我还是有点困惑。为什么添加return true; 不会覆盖function() 的返回值?
    • 忽略上面的评论 - 我现在明白了!再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 2013-07-03
    • 2015-09-14
    • 1970-01-01
    相关资源
    最近更新 更多