JQuery 将数字从函数传递给其他 JQuery 函数

JQuery passing number from function to other JQuery function

我有一些错误处理函数,我希望 return 错误的数量,以便我可以在另一个函数中处理。但是它没有按预期工作。有人有什么想法吗?

function validateForm() {
        // error handling
        var errorCounter = 0;

        $(".required").each(function(i, obj) {

            if($(this).val() === ''){
                $(this).parent().addClass("has-error");
                return errorCounter++;
            } else {
                $(this).parent().removeClass("has-error");
                return errorCounter;
            }

        });
    }

其他功能:

function actionCreateInvoice(){

        validateForm(errorCounter);

        if (errorCounter > 0) {
            $("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
            $("#response .message").html("<strong>Error</strong>: It appear's you have forgotten to complete something!");
        } else {
            ..... do something here once validated
}

将此 return errorCounter; 放在 .each 之外。

function validateForm() {
    // error handling
    var errorCounter = 0;

    $(".required").each(function(i, obj) {

        if($(this).val() === ''){
            $(this).parent().addClass("has-error");
            errorCounter++;
        } else{ 
            $(this).parent().removeClass("has-error"); 
        }


    });

    return errorCounter;
}

像这样调用你的函数:

function actionCreateInvoice(){
     var errorCounter = validateForm();//do not pass errorCounter as parameter