未定义的父对象

时间:2013-10-06 01:19:09

标签: javascript object undefined

我正在编写一个Family Tree应用程序,但我无法动态地将子项与父项连接起来。我一直收到父母未定义的错误。由于使用了相同的函数来创建父项,因此在重新调用函数时,除了将其传递给变量名之外,我还失去了如何识别父项。

非常感谢任何可以指引我朝着正确方向前进的人。我显然不太熟悉javascript。

更新:我能够通过将每个函数调用分配给适当的名称变量来解决问题。感谢@Oriol的帮助!

var rafael_bravo = addFamilyMember("rafael_bravo", "Rafael Bravo", "-", "-", "-", god, "GeneralPartner");
var calixta_otero = addFamilyMember("calixta_otero", "Calixta Otero", "-", "-", "-", rafael_bravo, "LimitedPartner");
var omar_bravo = addFamilyMember("omar_bravo", "Omar Bravo", "-", "-", "-", rafael_bravo, "LimitedPartner");


    function addFamilyMember (child,name,dob,dod,img,parent,link) {

                    child = new primitives.orgdiagram.ItemConfig();
                    child.name = name;
                    child.birth = dob;
                    child.death = dod;
                    child.image = "includes/images/" + img + ".png";
                    child.templateName = "familyTemplate";
                    parent.items.push(child);

                    jQuery(".basicdiagram").orgDiagram("update", primitives.orgdiagram.UpdateMode.Refresh);
                    return child;
                }

1 个答案:

答案 0 :(得分:1)

您可以使用

var names = {};
function addFamilyMember (id,name,dob,dod,img,parentId,link) {
    var child = new primitives.orgdiagram.ItemConfig();
    child.name = name;
    child.birth = dob;
    child.death = dod;
    child.image = img ? "includes/images/" + img + ".png" : "";
    child.templateName = "familyTemplate";
    names[id] = child;
    names[parentId].items.push(child);
    jQuery(".basicdiagram").orgDiagram("update", primitives.orgdiagram.UpdateMode.Refresh);
    return child;
}
addFamilyMember("rafael_bravo", "Rafael Bravo", "-", "-", "", "god", "GeneralPartner");
addFamilyMember("calixta_otero", "Calixta Otero", "-", "-", "", "rafael_bravo", "LimitedPartner");
addFamilyMember("omar_bravo", "Omar Bravo", "-", "-", "", "rafael_bravo", "LimitedPartner");

另请注意,如果您使用"-"作为img,浏览器会尝试下载includes/images/-.png,因此最好使用虚假的内容(例如空字符串""或{{ 1}}或void(0))然后检查它。我使用了一个空字符串,但有些浏览器会尝试将当前页面作为图像下载,因此在创建图像时请更好地检查false