在javascript中遍历一棵树

时间:2013-04-10 05:52:50

标签: javascript

我在javascript中有一个变量,如下所示:

var treeNode = [{
    "id": "T1"
  }, {
    "id": "T2",
    "children": [{
        "id": "T3"
      }, {
        "id": "T4"
      }, {
        "id": "T5",
        "children": [{
            "id": "T6"
          }, {
            "id": "T7"
          }, {
            "id": "T8"
          }
        ]
      }, {
        "id": "T9"
      }, {
        "id": "T10"
      }
    ]
  }, {
    "id": "T11"
  }, {
    "id": "T12"
  }
];

节点t3,t4,t5,t6,t7,t8,t9,t10是节点t2的子节点。

每个节点都有一个取消激活的链接。当点击取消激活两个链接激活并删除create.after in image:

enter image description here

我想在父节点的所有子节点上创建相同的活动和删除链接。例如 如果我点击T5的去激活链接,那么激活和删除链接也将显示在T6,T7,T8上 和 如果我点击T2的去激活链接,那么激活和删除链接将显示在T3,T4,T5,T6,T7,T8,T9,T10上

我尝试了下面的递归代码。但我认为这不是一个正确的方法。请给出建议。

var objTreeNode = eval(treeNode);
trav(objTreeNode);

function trav(TreeNodeObj){
    var i=0;
    for (i=0;i<TreeNodeObj.length;i++){
        if(!TreeNodeObj[i].children){
            if(objID==TreeNodeObj[i].id(){ //if click on T2 then get T2 as objID
                document.getElementById('span_'+objID).innerHTML = '<a href="javascript:activate(\'' + objID + '\');">Activate</a>    <a href="javascript:deleteNode(\'' + objID
                Delete</a>';
            }
        }
        else{

            childObj = TreeNodeObj[i].children;

            trav(objTreeNode)
        }
    }

}

2 个答案:

答案 0 :(得分:0)

您的遍历代码错误,基本遍历应该看起来像

function trav(obj) {
    // do something with obj

    //traverse through the children and call trav for each child
    if (obj.children) {
        for (i = 0; i < obj.children.length; i++) {
            trav(obj.children[i])
        }
    }

}

我假设在取消激活某个项目时,您也希望停用其所有子项,在这种情况下尝试类似

var treeMap = {};
for (i = 0; i < TreeNodeObj.length; i++) {
    var obj = TreeNodeObj[i];
    treeMap[obj.id] = obj;
}

function deactivate(obj) {
    if (typeof obj == 'string') {
        obj = treeMap[obj];
    }
    document.getElementById('span_' + obj.id).innerHTML = '<a href="javascript:activate(\''
            + obj.id
            + '\');">Activate</a>    <a href="javascript:deleteNode(\''
            + obj.id + 'Delete</a>';

    if (obj.children) {
        for (i = 0; i < obj.children.length; i++) {
            deactivate(obj.children[i])
        }
    }
}

答案 1 :(得分:0)

您的递归代码应为something like this

function trav(node) {

    var i;

    //deactivate target node
    console.log('Deactivating node id: '+node.id);

    //do the same to it's children
    if(node.children){
        for(i=0;i<node.children.length;i++){
          trav(node.children[i]);  
        } 
    }

}

console.log('Kill T1');
trav(objTreeNode[0]); //T1

console.log('Kill T2');
trav(objTreeNode[1]); //T2

console.log('Kill T5');
trav(objTreeNode[1].children[2]); //T5

只需将console.log trav部分替换为表示停用的操作即可。该示例显示控制台中的正确节点(按 F12