如何使用jQuery从.each循环创建数组

如何从’.each循环’内部创建一个数组并在循环外部使用它?

我的.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 }); 

如何从所有var = ClassesToApply创建数组?

而且我怎么能用这个数组做点什么呢? 例如

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

如果你在each变量之外声明一个变量,它将在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. 

虽然正如其他人所示,但有很多方法可以显着缩短代码。

 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; } } 

你可以这样做:

 var arr = $( 'a.cur:not(.apply)', '.profile-nav' ).map( function () { return $( this ).prop( 'class' ).split( ' ' )[0]; }).get(); 
 var list = $(".profile-nav ul li a.cur:not(.apply)"); list.each(function(){ // do your thing! });