2011-10-13 18 views
8

Come posso creare un array dall'interno del ciclo '.each' e usarlo al di fuori del ciclo?Come creare un array dal ciclo .each con jQuery

mio .each loop:

 // Loop through all but button with class .apply 
     $('.profile-nav ul li a').not('.apply').each(function() { 

      // if currently loop through element has .cur class 
      if($(this).hasClass('cur')) { 


       //Get the first class of the match element     
       var ClassesToApply = $(this).prop('class').split(' ')[0]; 

      } 
      //How can I create an array from all ClassesToApply? 


      //var arr = jQuery.makeArray(ClassesToApply); 
      // This will create an array, but with one element only 

     }); 

Come si crea una matrice da tutto var = ClassesToApply?

E come posso fare qualcosa con questo array? esempio

$(allClasses from an array as a selectors).doStuff();

+0

otterrete un array di stringhe. Cosa vuoi fare con un simile array? I metodi jQuery vengono eseguiti su array che contengono elementi DOM, non stringhe. –

+0

Sto cercando di usare la stringa come selettore per mostrare/nascondere l'elemento con le classi THE SAME in div differenti. Filtraggio - sorta di. – Iladarsda

risposta

21

Se si dichiara una variabile al di fuori della each, sarà accessibile all'interno del each:

var yourArray = []; 
$('.profile-nav ul li a').not('.apply').each(function() { 
    if($(this).hasClass('cur')) { 
     yourArray.push($(this).prop('class').split(' ')[0]); 
    } 
}); 
//Here, yourArray will contain the strings you require. 

Anche se, come altri hanno dimostrato, ci sono modi per abbreviare il codice in modo significativo .

0
var list = $(".profile-nav ul li a.cur:not(.apply)"); 

list.each(function(){ 
    // do your thing! 
}); 
6

Si potrebbe fare:

var arr = $('a.cur:not(.apply)', '.profile-nav').map(function() { 
    return $(this).prop('class').split(' ')[0]; 
}).get(); 
+0

Ottimo esempio! Non ho mai usato ".map" prima, ho bisogno di esaminarlo. – Iladarsda

+0

Se OP vuole un array, non dimenticare di concatenare '.get()' o '.toArray()' dopo '.map()'. – user113716

+1

@ Ӫ _._ Ӫ Hai dimenticato, grazie. –

13
fxnReqValidation = function() { 
     var InputTagArray = new Array; 
     InputTagArray = document.getElementsByTagName("input"); 
     for (var iCnt = 1; iCnt <= InputTagArray.length; iCnt++) { 
      if ((g_Json[InputTagArray[iCnt].name].required == true) && (InputTagArray[iCnt].value == "")) { 
       $("#errormsg").text("please enter all required fields"); 
      } 
      return false; 
     } 
    } 
Problemi correlati