如何使用JavaScript或Jquery在HTML中创建类似于组的结构

时间:2013-06-15 09:52:03

标签: javascript jquery html

我有这样的数据源

var source = [
    {
        group: "g-one",
        item: "one"
    },
    {
        group: "g-one",
        item: "two"
    },
    {
        group: "g-one",
        item: "three"
    },
    {
        group: "g-two",
        item: "aaa"
    },
    {
        group: "g-two",
        item: "bbb"
    }
];

从此我需要创建一个像这样的结构

<div id='g-one'>
    <div>one</div>
    <div>two</div>
    <div>three</div>
</div>
<div id='g-two'>
    <div>aaa</div>
    <div>bbb</div>
</div>

请帮我解决这个问题

2 个答案:

答案 0 :(得分:2)

jQuery Way

首先将这些小组排除在外:

var groups = $.unique($.map(source, function (n) {
    return n.group;
}));

迭代groups数组并获得输出:

$.each(groups, function (i, data) {
    $("<div/>", {
        "id": data.group,
        "html": function () {
              var elmts = $.grep(source, function (a) {
                return a.group === data;
              });
              return $.map(elmts, function (n) {
                  return "<div>" + n.item + "</div>";
              }).join(" ");
         }
    }).appendTo("body");
});

演示:http://jsfiddle.net/hungerpain/nZTvp/6/

仅使用JavaScript

使用for循环迭代并创建元素。要获取字符串,请使用字符串连接。

    var group = source[0].group;
    var html = "<div id='" + group + "'>";
    var elemts = [];
    for (var i = 0; i <= source.length; i++) {
    if (i !== source.length) {
        if (group === source[i].group) {
            html += "<div>" + source[i].item + " </div>";
        } else {
            html += "</div>";
            elemts.push(html);
            group = source[i].group;
            html = "<div id='" + group + "'><div>" + source[i].item + " </div>";
        }
    } else {
        html += "</div>";
        elemts.push(html);
    }
}

演示:http://jsfiddle.net/hungerpain/nZTvp/5/

答案 1 :(得分:1)

var source = [ { group: "g-one", item: "one" }, { group: "g-one", item: "two" }, { group: "g-one", item: "three" }, { group: "g-two", item: "aaa" }, { group: "g-two", item: "bbb" } ]; 
    var a=new Array(); 
    for(var i=0;i<source.length;i++)
    {
        a[i]=source[i].group;   
    }
    b = {};
    for (var i = 0; i < a.length; i++) 
    {
        b[a[i]] = a[i];
    }
    c = [];
    for (var key in b) 
    {
        c.push(key);
    }
    var message = "";
    for(var i=0;i<c.length;i++)
    {
        message+="<div id = '"+c[i]+"'>"
        for(var j=0;j<source.length;j++)
        {
            if(c[i] == source[j].group)
            {
                message+="<div>"+source[j].item+"</div>";

            }


        }
        message+="</div>";
    }
    alert(message);