简体   繁体   English

javascript通过.children()项循环并保存到数组

[英]javascript loop through .children() items and save to array

I couldn't find any solution that would suit for me regarding this question, so excuse me if duplicating. 我找不到会适合我对于这个问题的任何解决方案,因此,如果复制原谅我。

I want to go through all .children() items and if some of those items meet condition I want to save those items in one array. 我想通过所有。孩子()项,如果一些这些项目的符合条件我想保存在一个阵列中的项目。 Here's the code to show exactly what I mean: 这里的确切说明我的意思的代码:

    var items = [],
        allitems = $('.iconImg').children(),
        obj;


    // console.log(allitems);

    $('#next4').on('click', function(e){

        e.preventDefault();

        for(var i=0; i<allitems.length; i++){

            var currItem = $(allitems[i]).attr('id'),
                currItemPosLeft = parseInt($('#'+currItem).css('left')),
                itemOffset = getOffset('#'+currItem),
                items = [],
                arrToSend = [];

                // console.log(currItem, '=>', currItemPosLeft);    

            if(currItemPosLeft >= 405){

                obj = {

                    obId: currItem,
                    obPos: itemOffset

                }


                items.push(obj);
                console.log(items);

            }                   


        }

This code gives me separately number of arrays of objects that met condition, but what I would like is one array to store these objects. 此代码给我单独数量能够满足条件的对象数组,但我想是为了存储这些对象一个阵列。

How can I do this? 我怎样才能做到这一点?

Thanks 谢谢

Ok, I solved it. 好的,我解决了。 I'm not sure why I complicated this much, it's super easy. 我不确定为什么要这么复杂,这非常容易。
So, the code would be: 因此,代码将是:

    var items = [],
    allitems = $('.iconImg').children().toArray(),
    obj;


    // console.log(allitems);

    $('#next4').on('click', function(e){

        e.preventDefault();

        $(allitems).each(function(i){

            var currItem = $(allitems[i]).attr('id'),
                currItemPosLeft = parseInt($('#'+currItem).css('left')),
                itemOffset = getOffset('#'+currItem);


            // console.log(currItem, '=>', currItemPosLeft);

            obj = {

                odId: currItem,
                obPos: itemOffset

            };

            if(currItemPosLeft >= 405){

                items.push(obj);

            }




        })

        console.log(items);


    })
    //end of #next4 click

just a demo to do things; 只是一个做事的演示;

var testData = [{id:1,data:'abc'},{id:2,data:'efg'},{id:3,data:'pqr'},{id:4,data:'xyz'}]

var res = []

testData.forEach(function(o){ 
       if(o.id % 2 == 0) { //your condition..
          res.push({nid:o.id, ndata: o.data}) 
       } 
});

DEMO: http://jsfiddle.net/dpst36xe/ 演示: http : //jsfiddle.net/dpst36xe/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM