开发者

Javascript Recursive function seems to exit after first pass

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.

开发者_JAVA技巧
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.


Add a var i=0 inside the function. You have scoping issues with i.

http://jsbin.com/ugoju4/12/edit


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


top is a global variable referring to the "top" window of the current frame set. Use a different variable name.


  1. Why you type "++i" in you for-statement? Use "i++"
  2. You are typing

    index[n].children === ""

try it with

index[n].children == ""

I think he never runs in the else-part.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜