2009-05-06 17 views
3

我有幾個類='CCC'的Div。我想要使​​用jQuery將所有這些div放入數組中,然後遍歷數組。如何做到這一點。jQuery循環

+1

的jQuery的文檔是真正偉大的,並不難理解。 http://docs.jquery.com/Main_Page – ullmark 2009-05-06 11:19:36

回答

4
// get an array of the divs (will act like one anyway) 
var divs = $('div.CCC'); 

// do something for each div 
divs.each(function() { 
    // this refers to the current div as we loop through  
    doSomethingWith(this); 
}); 

// or call your method on the array 
LoopThroughDivs(divs); 

另外,這些可以寫成一個單獨的語句(如果你只想做其中之一):

$('div.CCC').each(function() { 
    // this refers to the current div as we loop through  
    doSomethingWith(this); 
}); 

LoopThroughDivs($('div.CCC')); 
+0

任何想法如何使用你的代碼反向循環..如先挑選最後的div.ccc? – Hitz 2009-05-06 11:56:25

+0

$('div.CCC')。reverse()我認爲 – 2009-05-06 11:57:06

+0

顯示它不在覈心,但有很多插件,像http://lab.arc90.com/2008/05/jquery_reverse_order_plugin.php – 2009-05-06 11:59:08

7

隨着每()函數:

$(".CCC").each(function(i){ 
    alert(this.id + " is the " + i + "th div with this class"); 
}); 

http://docs.jquery.com/Each

編輯:

的要求:

function LoopTroughDivs(selector){ 
    $(selector).each(function(i){ 
    alert(this.id + " is the " + i + "th div with this class"); 
}); 
} 
+0

正如我所說,我首先想把它放在一個數組中。然後,我會將該數組傳遞給一個名爲LoopThroughDivss的函數,如下所示: Loopthroughdivss(divsarray); 請告訴我那個 – Hitz 2009-05-06 11:25:07

+0

的解決方案,在你的問題中不太清楚..我的解決方案可以很容易地用在一個函數中,該函數通過jquery選擇器傳遞一個參數。我會編輯我的答案 – 2009-05-06 11:38:38

+0

感謝您的解決方案 – Hitz 2009-05-06 11:44:40

1

如下:

LoopThroughDivs($('.CCC')); 

說真的,這就是全部。你可以使用jQuery列表作爲數組。

-1

如果你想要把它放在一個數組:

var divArray = new Array(); 
$('.CCC').each(function() { divArray.push(this); }); //add each div to array 
//loop over array 
for(i=0, x=divArray.length, i<x, i++){ 
    //divArray[i] refers to dom object, so you need to use a jquery wrapper 
    //for the jquery functions: 
    $(divArray[i]).animate('height', '100px').html("I'm div the "+i+'th div'); 
} 

然而要注意的jQuery對象本身是一個數組,所以你也可以這樣做:

for(i=0, x=$('.CCC').length, i<x, i++){ 
    $('.CCC')[i].animate('height', '100px').html("I'm div the "+i+'th div'); 
} 
+0

爲什麼這是downvoted?它按照OP的要求提供。 – 2009-05-06 11:37:07

+0

爲什麼使用200英尺的卡車運送球? – balexandre 2010-08-31 10:53:18

-1

迴路的每個元素,並把它進入你的陣列。

var yourArray = new Array(); 
$(".CCC").each(function(index, element){ 
    yourArray[i]=element; 
}); 

Loopthroughdivss(yourArray);