开发者

JavaScript recursive Element creation fails

I don't understand why this fails:

var recursiveElementGenerator = function (elem_spec) {
    elem = document.createElement(elem_spec.tag);

    if (elem_spec.children) {
        for (var i=0; i<elem_spec.children.length; i++) {
            var c_elem = elem_spec.children[i];
            var n_elem = recursiveElementGe开发者_高级运维nerator(c_elem);
            alert(elem===n_elem);
            elem.appendChild(n_elem);
        };
    };
    return elem;
};

The elem_spec object has tag and children attributes, the latter being an array of similar objects.

This fails because the element returned by the recursive call is the same as the element created before that recursive call. Which I don't get -- a similar version works, by getting its chain of tag values from a pop() call on an array that is then passed into the recursive call.


Try using:

var elem = document.createElement(elem_spec.tag);

instead of:

elem = document.createElement(elem_spec.tag);

Not using the var keyword makes your variable operate on the global scope. Using it will create the variable in the local scope, from the line it's created to the end of your function definition.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜