如何从'.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
创建数组?
而且我怎么能用这个数组做点什么呢? e.g
$( allClasses from an array as a selectors).doStuff();
答案 0 :(得分:24)
如果您在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.
虽然正如其他人所示,但有很多方法可以显着缩短代码。
答案 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;
}
}
答案 2 :(得分:8)
你可以这样做:
var arr = $( 'a.cur:not(.apply)', '.profile-nav' ).map( function () {
return $( this ).prop( 'class' ).split( ' ' )[0];
}).get();
答案 3 :(得分:0)
var list = $(".profile-nav ul li a.cur:not(.apply)");
list.each(function(){
// do your thing!
});