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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7753182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:27:46  来源:igfitidea点击:

How to create an array from .each loop with jQuery

javascriptjquery

提问by Iladarsda

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

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

My .each loop:

我的.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

        });

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

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

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

比我怎么能用这个数组做点什么?例如

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

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

回答by James Allardice

If you declare a variable outside of the each, it will be accessible inside the each:

如果您在 之外声明一个变量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.

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

尽管正如其他人所展示的,有一些方法可以显着缩短您的代码。

回答by Anshu

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

回答by ?ime Vidas

You could do:

你可以这样做:

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

回答by BGerrissen

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

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