2010-12-03 63 views
0

我试图通过设置一个节点(索引)递归时渲染树状分层结构。我已经知道根源(top)。有多个根元素。我想收集变量整个HTML(这整个HTML将被追加到后面一个div)Javascript递归函数似乎在第一次通过后退出

tree = ""; 
top = ["1", "11", "14", "17", "72", "73", "74", "78", "79", "98", "99"]; 
index = { 
    1: { 
     'name': "Node 1", 
     'children': "2,3,4,5,6,7,8,9,10" 
    }, 
    2: { 
     'name': "Node 2", 
     'children': "" 
    }, 

//.... goes all the way upto 99 
} 

递归函数makeFT(指数,根)似乎只穿越后孩子打破“顶部”数组中的第一个元素。代码为jsbin及以下。可能是什么问题呢?有一个更好的方法吗?任何帮助表示赞赏。

makeFT(index, top); 


function makeFT(index, roots) { 
    console.log(roots); 
    tree == "" ? tree += '<ul>' : tree += '<ul><hr/>' 
    for (i = 0; i < roots.length; ++i) { 
     n = parseInt(roots[i]); 
     //console.log(n); 
     //console.log(index[n]); 

     tree += '<li>' + roots[i] + '</span>' + index[n].name; 

     if (index[n].children === "") { 
      tree += '<input class="leaf tree-first-input" type="text" size="2">' 
     } 
     else { 
      tree += '<input class="non-leaf tree-first-input" type="text" size="2">' 
      makeFT(index, index[n].children.split(",")); 
     } 
     tree += "</li>" 
    } 
    tree += '</ul><br/>' 

} 

更新:原来这是一个范围问题,而不是一个递归问题。递归是正常的。由于在循环遍历根数组时,我没有定义变量'i'的范围,因此每个后续递归函数都会继承unscoped'i'的值,从而产生问题。

回答

0

您不会从递归函数中返回任何东西。

} 
     else { 
      tree += '<input class="non-leaf tree-first-input" type="text" size="2">' 
      tree += makeFT(index, index[n].children.split(",")); 
     } 
     tree += "</li>" 
    } 
    tree += '</ul><br/>' 
    return tree; 
} 

这应该给你的价值。用它通过Id将它写入一个元素。更新了jsfiddle

+0

我认为tree是一个全局定义的变量,所以这个函数不能返回任何值。 – EvilMM 2010-12-03 12:21:28

+0

不管我是否返回值,都会发生此问题。试试自己。 – papdel 2010-12-03 12:23:35

+0

@EvilMM - 正确 – papdel 2010-12-03 12:24:03

-1
  1. 为什么在你的for语句中键入“++ i”?用 “我++”
  2. 你打字

    指数[N]。孩子=== “”

index[n].children == "" 

尝试它,我觉得他从来没有在运行else部分。

0

top是一个全局变量指的是当前帧组的“顶”的窗口。使用不同的变量名称。