【问题标题】:JQuery passing number from function to other JQuery functionJQuery 将数字从函数传递到其他 JQuery 函数
【发布时间】:2015-07-20 08:34:03
【问题描述】:

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

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
}

【问题讨论】:

    标签: javascript jquery error-handling


    【解决方案1】:

    将此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
    

    【讨论】:

    • @James 像这样调用你的函数:validateForm();
    • 宾果游戏!在 response.php 上收到 500 内部错误,但我会检查一下,但现在可以正常工作了!谢谢一群朋友!
    • @James 很高兴为您提供帮助,不要忘记标记答案:)
    • 我不会忘记别担心,我只是注意到它没有添加错误类...认为这可能是它在 repsonse.php 文件中抛出 500 错误?
    • 实际上它现在一起跳过验证,因为试图在 ajax 上处理 response.php 有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 2010-09-27
    相关资源
    最近更新 更多