<script>
var TreeNode = function(id,name,parent,children)
{
this.id = id,
this.name = name,
this.parent = parent,
this.children = children
}
var tnRoot = new TreeNode(0,"root",null,[]);
var tnChild1 = new TreeNode(5,"childNode1",tnRoot,[]);
var tnChild2 = new TreeNode(6,"childNode2",tnRoot,[]);
var tnChild3= new TreeNode(7,"childNode3",tnRoot,[]);
var tnLeaf1 = new TreeNode(10,"leafNode1",tnChild1,[]);
var tnLeaf2 = new TreeNode(11,"leafNode2",tnChild1,[]);
var tnLeaf3 = new TreeNode(12,"leafNode3",tnChild2,[]);
var tnLeaf4 = new TreeNode(13,"leafNode4",tnChild3,[]);
tnChild1.children = [tnLeaf1,tnLeaf2];
tnChild2.children = [tnLeaf3];
tnChild3.children = [tnLeaf4];
tnRoot.children = [tnChild1,tnChild2,tnChild3];
var sTNNameList = "";
function GetChildrenByParent(tnNode)
{
if(tnNode.children.length > 0)
{
for(var i=0;i<tnNode.children.length;i++)
{
sTNNameList += tnNode.children[i].name;
GetChildrenByParent(tnNode.children[i]);
}
}
else
{
sTNNameList += tnNode.name;
}
}
GetChildrenByParent(tnRoot);
alert(sTNNameList);
</script>我想实现通过GetChildrenByParent()方法得到一个对象下面的所有children的名称,我现在的方法有问题,哪位高手能帮我改一下,谢谢了
var TreeNode = function(id,name,parent,children)
{
this.id = id,
this.name = name,
this.parent = parent,
this.children = children
}
var tnRoot = new TreeNode(0,"root",null,[]);
var tnChild1 = new TreeNode(5,"childNode1",tnRoot,[]);
var tnChild2 = new TreeNode(6,"childNode2",tnRoot,[]);
var tnChild3= new TreeNode(7,"childNode3",tnRoot,[]);
var tnLeaf1 = new TreeNode(10,"leafNode1",tnChild1,[]);
var tnLeaf2 = new TreeNode(11,"leafNode2",tnChild1,[]);
var tnLeaf3 = new TreeNode(12,"leafNode3",tnChild2,[]);
var tnLeaf4 = new TreeNode(13,"leafNode4",tnChild3,[]);
tnChild1.children = [tnLeaf1,tnLeaf2];
tnChild2.children = [tnLeaf3];
tnChild3.children = [tnLeaf4];
tnRoot.children = [tnChild1,tnChild2,tnChild3];
var sTNNameList = "";
function GetChildrenByParent(tnNode)
{
if(tnNode.children.length > 0)
{
for(var i=0;i<tnNode.children.length;i++)
{
sTNNameList += tnNode.children[i].name;
GetChildrenByParent(tnNode.children[i]);
}
}
else
{
//sTNNameList += tnNode.name;
}
}
GetChildrenByParent(tnRoot);
alert(sTNNameList);
</script>
去掉sTNNameList += tnNode.name;就可以了
然后逻辑上有点点,加了else后在for循环中反复的调用事件 这样你输出的结果也就有问题了