2012-08-15 760 views
2

我有一個執行多次的函數。我想要使​​用jQuery調用函數多少次。我怎麼做?jQuery計算使用.each函數進行循環的次數

每當文本字段發生更改時,都調用showErrors函數。因此,根據頁面上文本字段的數量,我應該能夠找到調用showErrors的次數。我將如何檢測showErrors函數中的內容。

showErrors: function(errorMap, errorList) { 
    if ($formEl.find(".aimInput input").length == 2) { 
     // $('.validate').html(errorList[0]['message']); 
     $(".aimLocal .submit").removeClass("disabled"); 
     $(C.options.currentPage).find('input[type="submit"]').removeAttr("disabled"); 
    } 
} 
+3

你的代碼是怎樣的? – Shyju 2012-08-15 20:05:05

回答

4
var errors = 0; 

(...) 

showErrors: function(errorMap, errorList) {                            

    if($formEl.find(".aimInput input").length == 2) {  
     // $('.validate').html(errorList[0]['message']); 

     $(".aimLocal .submit").removeClass("disabled");        
     $(C.options.currentPage).find('input[type="submit"]').removeAttr("disabled"); 

     errors++; // <--------------- THIS 

    }      
} 

的數量在此之後,你可以在你的代碼中使用errors任何地方,因爲它是全球性的。

4
var i = 0; 

$("div").each(function() { 
    ... 
    i++; 
}); 

alert(i); 
+1

'$(「div」).length''怎麼樣? OP說其功能..他的職位和職位不是很清楚。 – 2012-08-15 20:06:47

+0

@Vega的好處,但處理程序可能被稱爲多次在這些'divs',所以有3'div'-s但功能運行9次,例如 – 2012-08-15 20:08:53

+0

哈哈@Vega,好點:P – 2012-08-15 20:09:09

3

jQuery的爲您處理此。試試這個:

$("something").each(function(index) { 
    alert("Current index is " + index); 
}); 
+0

謝謝這是它,沒有理由宣佈另一個變種 – vcazan 2015-08-28 16:31:01

0

您可以簡單地計算元素

$("#foo > div").length 
+0

我一開始也這麼認爲,但後來我覺得他可能是在尋找一個跑步總數 – 2012-08-15 20:08:40