动态创建嵌套数组

时间:2010-03-18 21:29:45

标签: javascript jquery arrays loops

我想要做的是循环这个HTML并获取我想要抓取的这个HTML值的嵌套数组。

一开始可能看起来很复杂 但这是一个简单的问题...

HTML

<div class="configureData">
               <div title="Large">
                  <a href="yellow" title="true" rel="$55.00" name="sku22828"></a>
                  <a href="green" title="true" rel="$55.00" name="sku224438"></a>
                  <a href="Blue" title="true" rel="$55.00" name="sku22222"></a>
                </div>
              <div title="Medium">
                  <a href="yellow" title="true" rel="$55.00" name="sku22828"></a>
                  <a href="green" title="true" rel="$55.00" name="sku224438"></a>
                  <a href="Blue" title="true" rel="$55.00" name="sku22222"></a>
                </div>
             <div title="Small">
                  <a href="yellow" title="true" rel="$55.00" name="sku22828"></a>
                  <a href="green" title="true" rel="$55.00" name="sku224438"></a>
                  <a href="Blue" title="true" rel="$55.00" name="sku22222"></a>
             </div>
   </div>

的javascript

  //This script is just part of a Object containing methods.
parseData:function(dH){
        dH.find(".configureData div").each(function(indA, eleA){
                   colorNSize.tempSizeArray[indA] = [eleA.title,[],[],[]]
                     $(eleZ).find("a").each(function(indB, eleB){
                              colorNSize.tempSizeArray[indA][indB] = eleB.title
              })
            })
        },

我希望最终的数组看起来像这样。

 [
   ["large", 
      ["yellow", "green", "blue"],
      ["true", "true", "true"],
      ["$55", "$55","$55"]
   ],
   ["Medium", 
      ["yellow", "green", "blue"],
      ["true", "true", "true"],
      ["$55", "$55","$55"]
   ]
 ]
// and so on....

2 个答案:

答案 0 :(得分:2)

鉴于您的HTML和此jQuery代码段:

var result = [];
$('.configureData div').each(function () {
    var $a = $('a', this);
    result.push([this.title,
            $.map(['href', 'title', 'rel'], function (a) {
                return [$.map($a, function (v) {
                    return $(v).attr(a)
                })];
            })

    ]);
});

您按照提问的方式设置result

如果您有Firebug,请执行console.dir(result)并查看。

编辑:我更新了脚本以将任意属性提取到单独的子数组

答案 1 :(得分:1)

这样的事情应该有效。 (你的代码并不太远。)

parseData:function(dH){
  var results = [];
  dH.find(".configureData div").each(function(indA, eleA){
    var div = $(this);
    var result = [div.attr('title'),[],[],[]];
    results[results.length] = result;
    div.find("a").each(function(indB, eleB){ 
      var link = $(this);
      result[1][result[1].length] = link.attr('href');
      result[2][result[2].length] = link.attr('title');
      result[3][result[3].length] = link.attr('rel');
    });
  });
}