Reputation: 7081
I am trying to render a tree like hierarchy while recursing through set a nodes (index). I already know the roots(top). There are multiple root elements. I am trying to collect the entire html in the variable tree (this entire html will be appended to a div later)
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
}
The recursive function makeFT(index,roots) only seems to break after traversing the children of first element in the "top" array.
The code for this is at jsbin and below. What could be the problem? Is there a better way to do this? Any help is appreciated.
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/>'
}
UPDATE : Turns out this is a scoping problem and not a recursion problem. The recursion was alright. Since I did not define scope of the variable 'i' while looping through roots array, each subsequent recursed function inherited the value of unscoped 'i' thereby creating the problem.
Upvotes: 0
Views: 808
Reputation: 38400
top
is a global variable referring to the "top" window of the current frame set. Use a different variable name.
Upvotes: 0
Reputation: 8390
Add a var i=0 inside the function. You have scoping issues with i.
http://jsbin.com/ugoju4/12/edit
Upvotes: 4
Reputation: 901
You are typing
index[n].children === ""
try it with
index[n].children == ""
I think he never runs in the else-part.
Upvotes: -1
Reputation: 17472
You are not returning anything from your recursive function.
}
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;
}
This should give you the value. Use it to write it to an element by Id. Updated the jsfiddle
Upvotes: 0