无法在每个父div / class中获取子div ID

时间:2014-07-31 00:52:17

标签: javascript jquery multidimensional-array

当我尝试在每个父div / class中获取子div ID时,我得到错误“未捕获的TypeError:无法设置未定义的属性'0'”。我正在使用这个javascript与scriptaculous,所以我关闭了“$”快捷方式。

示例HTML:

<div id="group1" class="section">
     <h3 class="handle"><input type="hidden" name="groupName1" value="MyGroup1">MyGroup1</h3>

    <div id="item_73548" class="lineitem">item a</div>
    <div id="item_73386" class="lineitem">item b</div>
    <div id="item_73163" class="lineitem">item c</div>
</div>
<div id="group2" class="section">
     <h3 class="handle"><input type="hidden" name="groupName2" value="MyGroup2">MyGroup2</h3>

    <div id="item_73548" class="lineitem">item d</div>
    <div id="item_73386" class="lineitem">item e</div>
    <div id="item_73163" class="lineitem">item f</div>
</div>

Javascript:

$.noConflict();
var sections = document.getElementsByClassName('section');

var groups = new Array();

for (i = 0; i < sections.length; i++) {
    var section = sections[i];
    var sectionID = section.id;

    var j = 0;

    jQuery.each(jQuery("#" + sectionID + " .lineitem"), function () {

        groups[i][j] = jQuery(this).attr('id');
        j++;

    });

}

console.log(groups);

输出应为:

groups[0][0]="item_73548";
groups[0][1]="item_73386";
groups[0][2]="item_73163";
groups[1][0]="item_73548";
groups[1][1]="item_73386";
groups[1][2]="item_73163";

在这里小提琴:http://jsfiddle.net/qy9dB/3/

1 个答案:

答案 0 :(得分:1)

在尝试将第二级元素添加到数组之前,您只需要确保将groups[i]设置为数组。

$.noConflict();
var sections = document.getElementsByClassName('section');

var groups = new Array();

for (i = 0; i < sections.length; i++) {
    var section = sections[i];
    var sectionID = section.id;

    groups[i] = [];

    var j = 0;

    jQuery.each(jQuery("#" + sectionID + " .lineitem"), function () {

        groups[i][j] = jQuery(this).attr('id');
        j++;

    });

}

console.log(groups);