【问题标题】:Multidimensional Array from HTML using jquery使用 jquery 来自 HTML 的多维数组
【发布时间】:2014-09-28 07:01:36
【问题描述】:

我在页面上重复了 div。我需要选择外箱 ID 和文本元素

<div class="outerbox" id="12345">

        <div class="headerbox" id="title12345">

            <div class="text">&nbsp;</div>
            <h2>Foo Bar
            </h2>
        </div>

我需要使用 jquery 创建一个多维数组

到目前为止,我已经为外盒 ID 创建了一个数组

var boxids = $('.outerbox').map(function() { return this.id; }).get();
var boxidsLength = boxids.length;

var i = 0; i < boxidsLength; i++) {
    alert (boxids[i])
}

但是我很难理解如何 1) 我将从此输入创建一个多维数组以及如何 2) 选择“文本”类下的元素

数组看起来像

Foo Bar | Bar Foo

12345   | 67890

谢谢

【问题讨论】:

  • 如果可能的话,可以发布所需数组的文字[[]] 吗?不确定 "The array would look like" Foo Bar | Bar Foo 12345 | 67890 的结果描述? [id, text] ?谢谢
  • 抱歉,我理解二维数组的布局类似于电子表格 [Foo Bar[1234] Bar Foo [4567]] 将是理想的输出,因此我可以将它们称为 array[0][ 0] 并得到 Foo Bar 然后 array[0][1] 得到 1234

标签: javascript jquery arrays multidimensional-array


【解决方案1】:

编辑、更新

试试

var boxids = $('.outerbox').map(function() { 
  return [[$.trim($(".text + *", this)[0].innerText), this.id]] ; 
}).get();

var boxids = $('.outerbox').map(function() { 
  return [[$.trim($(".text + *", this)[0].innerText), this.id]] ; 
}).get();
$("body").text(boxids);
console.log(boxids);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="outerbox" id="12345">

        <div class="headerbox" id="title12345">

            <div class="text">&nbsp;</div>
            <h2>Foo Bar
            </h2>
        </div>
    
    <div class="outerbox" id="67890">

        <div class="headerbox" id="title678905">

            <div class="text">&nbsp;</div>
            <h2>bar foo
            </h2>
        </div>

【讨论】:

  • 重复此框时我错过了什么?见jsfiddle.net/z183gfpx
  • 不确定“失踪”是什么意思? console.log(boxids[0][0], boxids[0][1], boxids[1][0], boxids[1][1]); ?
  • 如果上面的“outerbox”代码有两个实例,一个称为 foo bar,一个称为 bar foo,具有不同的 ID,我得到 [foo bar bar foo[12345][foo bar bar foo[ 67890]]
【解决方案2】:

我认为这应该可行:

var array = [];
$('.outerbox').each(function ()
{
    var id = this.id;
    var text = $(this).find('.text').next().text();

    array[text] = id;
});

但也许您需要清理text,以修剪空格和换行符。

【讨论】:

    猜你喜欢
    • 2019-10-26
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2016-10-05
    • 1970-01-01
    相关资源
    最近更新 更多