2013-10-15 37 views
0

經過一番研究,我似乎無法找到任何信息來檢查您是否在循環結束。我特別想知道你是否可以在jQuery中使用.each()來檢查它。我想實現的是如何檢查您是否在循環結束?

$("tr#row"+formIdentifier).find('td').each(function(){ 
    if (last_item_in_loop){ 
     alert("this is the last item in the loop"); 
    } 
}); 

到目前爲止,它遍歷好吧,我只是希望能夠提醒到,他們是在最後一個項目的用戶。任何幫助將不勝感激。先謝謝你!

+2

什麼是一個自豪的證明,使用jQuery的一切並不總是讓事情變得簡單。 – mavrosxristoforos

+0

是否有任何具體的原因,爲什麼最後選擇器不使用,而不是循環? – Miller

回答

2

我不這麼認爲,你必須在自己的項目和重複檢查的最後一個索引。如果你想這樣做,你處理的最後一個元素之後,你可以只添加過程的循環下面的代碼...

var elements = $("tr#row"+formIdentifier).find('td'); 
for (var i = 0; i < elements.length; i++) { 
    if (i == elements.length - 1) { 
     alert("this is the last item in the loop"); 
    } 
    // normal stuff 
} 
+0

謝謝你的幫助。這幫助我繼續!謝謝你謝謝你的建議! –

1

使用$("tr#row"+formIdentifier).find('td').length獲得數

$("tr#row"+formIdentifier).find('td').each(function (index,value){ 

    if(index == $("tr#row"+formIdentifier).find('td').length) 
    ..................... 
}); 
+0

和'each'回調參數來獲取當前編號。 – vittore

+0

每個給你的迭代索引 – mkoryak

1

您可以使用一個簡單的條件這樣

var $tds = $("tr#row"+formIdentifier).find('td'); 
var $last = $tds.last(); 
$tds.each(function(){ 
    if ($last.is(this)){ 
     alert("this is the last item in the loop"); 
    } 
}); 

或者使用索引條件

var $tds = $("tr#row"+formIdentifier).find('td').each(function (idx){ 
    if (idx == $tds.length - 1){ 
     alert("this is the last item in the loop"); 
    } 
}); 
+1

這可能不太好,因爲.last()不會在每個循環中被緩存和重新計算... – mkoryak

+0

@mkoryak更新爲使用緩存值 –

+0

現在簡單條件變得不那麼簡單了;) – mkoryak

0

你可以做這樣的:

var elements = $('td', 'tr#row' + formIdentifier), 
    total = elements.length; 

for (var i = 0; i<total; i++) { 
    if (i === (total-1)) { 
     alert("this is the last item in the loop"); 
    } 
}