2013-04-17 3 views
2

Я просматриваю свой HTML-файл с помощью jQuery, чтобы собирать элементы. Затем я хочу выполнить операцию jQuery для каждого найденного элемента. Это то, что у меня есть до сих пор, но оно не работает, поскольку я не знаю, как хранить элементы jQuery из каждого метода. Может кто-нибудь помочь?Сбор элементов jQuery в коллекции

var foundElems = []; 
$('#some-container .some-class').each(function(index) { 
    //filter $(this) 
    //store $(this) 
    foundElems.push($(this)); 
}); 
$('#some-container2 .some-class2').each(function(index) { 
    //filter $(this) 
    //store $(this) 
    foundElems.push($(this)); 
}); 
//do this again for many containers.... 

//then call some jQuery function on each element of that collection 
foundElems.fadeOut('slow'); 

ответ

1

Вы можете выбрать несколько элементов, разделяя их с ,.

$('#some-container .some-class, #some-container2 .some-class2').fadeOut('slow'); 

Если у вас есть, чтобы разместить кучу этих элементов можно построить массив с селекторами и проход, присоединившихся массив в функцию JQuery.

var arr = ["#some-container2 .some-class2","#some-container .some-class"]; 
$(arr.join(",")).fadeOut('slow'); 

Рабочий примерhttp://jsfiddle.net/mBtKg/

0

Использование $.merge()

var foundElems = $(); 
$('#some-container .some-class').each(function(index) { 
    //filter $(this) 
    //store $(this) 
    foundElems=$.merge(foundElems,$(this)); 
}); 
$('#some-container2 .some-class2').each(function(index) { 
    //filter $(this) 
    //store $(this) 
    foundElems=$.merge(foundElems,$(this)); 
}); 
//do this again for many containers.... 

//then call some jQuery function on each element of that collection 
foundElems.fadeOut('slow'); 

Вы также можете объединить все ваши запросы селекторные с запятой:

var foundElems = $(); 
$('#some-container .some-class,#some-container .some-class2,#some-container .some-class3').each(function(index) { 
    //filter $(this) 
    //store $(this) 
    foundElems=$.merge(foundElems,$(this)); 
}); 


//then call some jQuery function on each element of that collection 
foundElems.fadeOut('slow'); 
0

Ваш jQuery кажется прекрасным, к концу ваших .each-операторов вы должны иметь массив элементов. Ваша проблема заключается в том, что вы не можете вызвать .fadeOut на свой объект массива.

Вы должны сделать это:

$.each(foundElems, function() { 
    $(this).fadeOut("slow"); 
}); 
0

Самое простое решение, которое я мог думать:

var array; 
array = $.merge($(),$.find('#someContainer .someClass, #someContainer2 .someClass2')); 
array.fadeOut(1000);