2011年3月24日星期四

[Java Script]用递归方式绘制树

topology_array数组对象中存有一棵树所包含节点父子关系,通过get_topology_html生成jquery树插件所需HTML代码,最终实现树的绘制。

var topology_array = new Array(
// "switch", "designated switch", "if-traversed"
["ANDERS", "ROOT", 0],
["CINDY", "ANDERS", 0],
["DAVID", "ANDERS", 0],
["ERIC", "ANDERS", 0],
["FRANK", "ANDERS", 0],
["BILL", "ROOT", 0],
["GATES", "BILL", 0],
["HAVORD", "BILL", 0],
["IAN", "BILL", 0],
["JACK", "BILL", 0],
["KARAN", "CINDY", 0],
["LERRY", "KARAN", 0],
["MIKE", "LERRY", 0],
[ 0, 0, 0]
);

function sub(data, node)
{
for (i = 0; i <> if(data[i][1] == node && data[i][2] != 1) {
//alert(data[i][0]);
data[i][2] = 1;
return data[i][0];
}
}
return -1;
}

function get_topology_html(data, root)
{
var ret;

while((ret = sub(data, root)) != -1) {
topology_html += "<><>";
topology_html += ret;
get_topology_html(data, ret);
topology_html += "< /li >< /ul >";
}
}