цикл jQuery - PullRequest
       32

цикл jQuery

3 голосов
/ 06 мая 2009

У меня есть пара Div с class = 'CCC'. Я хочу взять все эти div в массив, используя jQuery, а затем перебрать массив. Как это сделать.

Ответы [ 5 ]

7 голосов
/ 06 мая 2009

С функцией Each ():

$(".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");
 });
}
4 голосов
/ 06 мая 2009
// 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'));
1 голос
/ 06 мая 2009

выглядит так:

LoopThroughDivs($('.CCC'));

Серьезно, это все, что есть. Вы можете использовать список jQuery как массив.

0 голосов
/ 06 мая 2009

Зациклите каждый элемент и поместите его в свой массив.

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

Loopthroughdivss(yourArray);
0 голосов
/ 06 мая 2009

Если вы хотите поместить его в массив:

 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');
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...