2015-05-09 56 views
-2

我有一些錯誤處理函數,我希望返回錯誤的數量,以便在另一個函數中處理。然而,它沒有按預期工作。有人有主意嗎?JQuery從函數傳遞數字到其他JQuery函數

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 
} 

回答

0

.each這個return errorCounter;之外。

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 
+0

即時得到errorCounter沒有定義? – James

+0

@James像這樣調用你的函數:'validateForm();' – renakre

+0

是的,我做到了,儘管如此。 – James