2011-10-13 42 views
8

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

.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();

+0

你会得到一个字符串数组。你想用这样一个数组做什么? jQuery方法在包含DOM元素的数组上执行,而不是字符串。 –

+0

我正在寻找使用字符串作为选择器来显示/隐藏与不同div中的SAME类的元素。过滤 - 有点。 – Iladarsda

回答

21

如果申报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. 

虽然如其他人已经表明,有很多方法可以显著缩短你的代码。

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

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

你可以这样做:

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

很好的例子!我以前从未使用'.map',我需要查看它。 – Iladarsda

+0

如果OP想要一个数组,不要忘记在'.map()'之后链接'.get()'或'.toArray()'。 – user113716

+1

@Ӫ_._Ӫ忘了那个,谢谢。 –

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