1

我有以下无序列表:

<ul class="primary">
    <li id="1"><span>Product Family A</span>
       <ul class="secondary">
           <li><span>A.1</span></li>
           <li><span>A.2</span></li>
       </ul>
    </li>
    <li id="2"><span>Product Family B</span>
       <ul class="secondary">
           <li><span>B.1</span></li>
       </ul>
    </li>
    etc...
</ul> 

我想用 jQuery 生成下面的输出。有人可以帮忙吗?

product_family:[{
   id:1,
   products:[{
      model: A1,
      model: A2
}],
product_family:[{
   id:2,
   products:[{
      model: B1
}]

谢谢!

4

2 回答 2

1
var out = [];
$('ul.primary > li').each(function(index, val) {
    out[index] = {
        product_family : this.id,
        products: []
    };
    $('ul > li', this).each(function() {
        out[index].products.push({
            model: $('span', this).text()
        });
    })
});
于 2012-05-16T16:39:31.917 回答
0

请注意,这部分是无效的:

products:[{
    model: A1,
    model: A2
}],

我假设你打算写这个:

products:[
    { model: A1 },
    { model: A2 }
}],

你可以使用这样的东西:

var pf = [];
$("ul.primary").children("li").each(function(i,e) {
    var products = [];
    $(e).find('ul').find('span').each(function(i2,e2) {
        products.push({ model: $(e2).find('ul') });
    });
    pf.push( {
        id: (i+1),
        products: products
    });
});
于 2012-05-16T16:40:34.017 回答