【问题标题】:Can't get child div IDs within each parent div/class无法在每个父 div/类中获取子 div ID
【发布时间】:2014-07-31 08:57:56
【问题描述】:

当我尝试在每个父 div/类中获取子 div ID 时,我收到错误“Uncaught TypeError: Cannot set property '0' of undefined”。我正在使用这个带有 scriptaculous 的 javascript,所以我关闭了“$”快捷方式。

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

【问题讨论】:

  • 为什么要混合原生 DOM 访问和 jQuery?使用 jQuery.forEach 获取您的部分,然后在每个 jQuery 部分对象上执行选择器以获取您的 div 子项$('.lineitem', this).attr('id');
  • 同意,这是一个更大的遗留脚本的一小部分,它使用 scriptaculous 库用纯 JavaScript 编写。所以我只是在我改变的部分上使用 jQuery。我希望我有时间从头开始重写它。

标签: javascript jquery multidimensional-array


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    相关资源
    最近更新 更多