查找子类并将它们分组到父div上

时间:2014-08-05 23:14:24

标签: php jquery

我想在每个网页列出的每个母div中找到所有具有id的子类。 这样,子div的id应按mainID分组 - 与ajax帖子一起使用。

但是,我甚至不能在jquery 1.11中获得孩子的身份,更不用说将他们与mainID分组了。

这是到目前为止的代码:

$(".main-column-name").each(function() {
    var mainID = $(this).attr('id');

    var subid = $(this).find(".subdiv-name").attr("id");
    alert(mainID + ' ' + subid );
}); 

因此,在mainID下面应该是一组subID& - 如果它们当然存在的话。

欢迎任何帮助!!!

1 个答案:

答案 0 :(得分:0)

您可以将其写入对象数组,并将子项作为子数组附加到此对象。

var mainEl = $(".main-column-name")
    mainArr = [],
    childArr = [];

//set the properties in an array to be used later
mainEl.each(function() {

    var id = $(this).attr('id')
        children = $(this).find('.subdiv-name').attr('id');

    children.each(function() {
        //add the child IDs to an array
        childArr.push($(this).attr('id'))
    });

    //push all the properties into an array
    mainArr.push({ 'name': id, 'children': childArr });

});


//to access the properties, use a loop
$.each(mainArr, function (i, value) {

    //get the name
    console.log(mainArr[i].name);

    //get the children
    console.log(mainArr[i].children);

    //and to access the child IDs individually, use this loop within the loop
    $.each(mainArr[i].children, function(c, id) {

        //get the stored value for id
        console.log(id)
    });
});

尽管如此,请谨慎使用,因为如果有很多孩子和很多父母,在循环中运行循环可能会导致一些性能问题。除此之外,其他人可能会建议更好地提取这些信息......如果我自己想到一个更好的方法,我会更新,但我没有太多时间去研究它。

相关问题