开发者

how to get all child node in treeview of YUI

I want all the childs of given node in YUI treeview. Condition is that if the child has sub-childs then I want sub-sub-child. that is all the childs of given node including subchilds.

I think recursion may be the 开发者_C百科solution for this problem.Can anyone help me out this.

My current code is

if(curNode.hasChildren()) {
  for(var child = 0; child < curNode.children.length;child++) {
    alert(curNode.children[child].label);
   }
}

By this code, I only get the childrens of given node and not the sub-sub-child nodes.


var root = $("#root")[0];
var nodeList = [];

function appendChildren(node, array) {
    if (node.hasChildNodes()) {
        for (var i = 0; i < node.children.length; i++) {
            if (node.children[i].hasChildNodes()) {
                appendChildren(node.children[i], array);
                array.push(node.children[i]);
            }
        }
    }
}

appendChildren(root, nodeList);

Tested here.

A recursive solution. This can be done more elegantly using functional style programming. This one relies on underscore.js for a cross browser .reduce implementation. You can rely on array.reduce if you target newer browsers.

function nodeToChildren(node) {
    if (node.hasChildren()) {
        _.reduce(node.children, function (memo, val) {
            return memo.concat(nodeToChildren(val));
        }, [].concat(node));
    } else {
        return node;
    }
}

var array = nodeToChildren(root);

Give me a few moments to test/debug this.

I forgot the jQuery option

var array = $(root).find("*").toArray()


You can get the root node : var root = tree.getRoot(); tree_traversal(root);

Then you can get its children

function tree_traversal(node){
     if(node.hasChildren)    {
         var nodes = node.children;
         for(var i = 0; i < nodes.length; i++)    {
             var test_node = nodes[i];
             var label = test_node.label;

         }
     }

}

Make the above function recursive and there you go!!Bingo


getAllChildren: function (fromNode) { if (fromNode.hasChildren()) { for (var k in fromNode.children) { if (fromNode.children[k].hasChildren()) { CategoryMaster.getAllChildren(fromNode.children[k]); } nodeList.push(fromNode.children[k]); } } },

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜