开发者

How to create an array from .each loop with jQuery

开发者 https://www.devze.com 2023-04-13 05:52 出处:网络
How can I create an array from inside of the \'.each loop\' and use it outside of the loop? My .each loop:

How can I create an array from inside of the '.each loop' and use it outside of the loop?

My .each loop:

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

            // if currently开发者_Python百科 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

        });

How can I create an array from all var = ClassesToApply?

And than how can I do something with this array? e.g

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


If you declare a variable outside of the each, it will be accessible inside the 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.

Although as others have shown, there are ways to shorten your code significantly.


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


You could do:

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


var arraySelectors = $('.profile-nav ul li a.cur:not(.apply)')
                        .toArray()
                        .map(e => '.' + Array.from(e.classList).join('.'));

This snippet is probably not the most elegant but it tries to accomodate to the objective the OP was describing.

I prefer not splitting a className because you never know how many consecutive spaces there is.

Exiting from the jQuery array and getting to a native array seems to be the best solution.

  • Array.from() is ES6 circa 2015
  • jQuery.toArray() appeared in jQuery 1.4
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号