如何使用jQuery从.each循环创建数组 [英] How to create an array from .each loop with jQuery

查看:193
本文介绍了如何使用jQuery从.each循环创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的 .each循环

       // 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

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

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

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

$(作为选择器的数组中的allClasses).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.

这篇关于如何使用jQuery从.each循环创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆