基于先前生成的父对象生成子元素

时间:2015-04-27 03:47:28

标签: javascript

所以,JavaScript新手。目前,我有两个独立的对象类,如下面的“父母”和“儿童”所示。这些父项使用函数BuildObjects打印到页面。这很好用。但是,我还想根据每个对象的类别将Children对象打印到Parent对象中。

示例代码:

Parents=[];
Children=[];
Parent=function(name,desc)
{
    this.name=name;
    this.desc=desc;
    Parents[this.name]=this;
}

new Parent('Example 1','Example desc 1');
new Parent('Example 2','Example desc 2');
new Parent('Example 3','Example desc 3');

Child=function(name,desc,parentname)
{
    this.name=name;
    this.desc=desc;
    this.parentname=parentname;
    Children[this.name]=this;
}

new Child('Example 1 Child 1','Example desc 1','Example 1');
new Child('Example 1 Child 2','Example desc 2','Example 1');
new Child('Example 1 Child 1','Example desc 3','Example 2');
new Child('Example 2 Child 2','Example desc 4','Example 2');

function BuildObjects() {
    var out = '';
    for (var i in Parents) {
        out += '<p id="' + Parents[i].category + '">' + Parents[i].name + '</p><p>' + Parents[i].desc + '</p><p>';
    }
    document.getElementById("textcontainer").innerHTML = out;
}

我该怎么做呢?实现这个最容易扩展的方法是什么?我曾想过在父对象中创建一个子对象,但我不太清楚如何去做,或者甚至可能。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

为了便于访问,您可以维护另一个元对象,该对象将根据类别对子项进行分组,然后使用它来打印子项

Parents = {};
Children = {};
ChildrenCatMap = {};
Parent = function (name, desc, category) {
    this.name = name;
    this.desc = desc;
    this.category = category;
    Parents[this.name] = this;
}

new Parent('Example 1', 'Example desc 1', 'category1');
new Parent('Example 2', 'Example desc 2', 'category2');
new Parent('Example 3', 'Example desc 3', 'category3');

Child = function (name, desc, category) {
    this.name = name;
    this.desc = desc;
    this.category = category;
    Children[this.name] = this;
    if (!ChildrenCatMap[category]) {
        ChildrenCatMap[category] = [];
    }
    ChildrenCatMap[category].push(this);
}

new Child('Example 1', 'Example desc 1', 'category1');
new Child('Example 2', 'Example desc 2', 'category1');
new Child('Example 3', 'Example desc 3', 'category2');
new Child('Example 4', 'Example desc 4', 'category2');

function BuildObjects() {
    var out = '',
        children;
    for (var i in Parents) {
        out += '<p id="' + Parents[i].category + '">' + Parents[i].name + '</p><p>' + Parents[i].desc + '</p>';
        children = ChildrenCatMap[Parents[i].category];
        if (children) {
            out += '<ul>';
            for (var j in children) {
                out += '<li id="' + children[j].category + '">' + children[j].name + '</p><p>' + children[j].desc + '</li>';
            }
            out += '</ul>';
        }
        out += '<p>';
    }
    document.getElementById("textcontainer").innerHTML = out;
}
BuildObjects();

演示:Fiddle

相关问题