2012-04-23 77 views
6

在一个树状结构这样如何将子项添加到TreePanel中的节点?

var rootNode = { 
       id: 'root', 
       text : 'Root Node', 
    expanded : true, 
    children : [ 
    { 
     id : 'c1', 
     text : 'Child 1', 
     leaf : true 
    }, 
    { 
     id : 'c2', 
     text : 'Child 2', 
     leaf : true 
    }, 
    { 
     id : 'c3', 
     text : 'Child 3', 
     children : [ 
     { 
      id : 'gc1', 
      text : 'Grand Child', 
      children : [ 
      { 
       id : 'gc11', 
       text : 'Grand Child 1', 
       leaf : true 
      }, 
      { 
       id : 'gc12', 
       text : 'Grand Child 2', 
       leaf : true 
      } 
      ] 
     } 
     ] 
    } 
    ] 
}; 

var tree = new Ext.tree.TreePanel({ 
    id: 'treePanel', 
    autoscroll: true, 
    root: rootNode 
}); 

如何添加任何节点的子节点(说“孙子”)?

我可以通过遍历treepanel的根访问孩子,但我console.logged它在Firebug中,它没有任何功能。 对不格式化的代码抱歉,我无法格式化它。

Tree Panel

+0

要实际查看Firebug中的可用功能,请安装Illuminations for Developers - Firebug插件。对ExtJS开发非常有用。 – dbrin 2012-04-24 02:17:42

+0

我确实有:) – Shashwat 2012-04-27 06:04:39

回答

13

做这样的事情:

var treeNode = tree.getRootNode(); 
treeNode.expandChildren(true); // Optional: To see what happens 
treeNode.appendChild({ 
     id: 'c4', 
     text: 'Child 4', 
     leaf: true 
}); 
treeNode.getChildAt(2).getChildAt(0).appendChild({ 
     id: 'gc13', 
     text: 'Grand Child 3', 
     leaf: true 
}); 

如果这是你需要什么,看看NodeInterface类。它有很多有用的方法: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.NodeInterface

+0

它的工作!它有没有区别tree.root和tree.getRootNode()? – Shashwat 2012-04-24 08:08:11

+0

“root”配置适用于不希望将根数据存储并硬编码到该配置中的情况(如上面的代码)。之后,您可以在运行时使用getRootNode()方法返回您的根数据。在上面的链接处仔细阅读根'config'和getRootNode()'方法'。 – Natasha 2012-04-24 13:21:38

0

它可能是一个较老的线程,但是,我有一个问题,我添加了一个孩子到选定的节点。我想通过展开选定的节点来显示新的孩子,并且失败了。

原因:我追加一个孩子的选定节点的属性'leaf'设置为true。这是正确的。但由于追加,这不再是事实。显然,Ext拒绝扩展节点...

所以要小心:当您将节点添加到另一个节点时,请确保将parentNode的'leaf'属性设置为'false':

var newNode = Ext.create('some.model.TreeModel', savedNode); 
newNode.set('parentId', record.parentLocationId); 
selectedNode.set('leaf', false); 
selectedNode.appendChild(newNode); 
selectedNode.expand(); 
treeView.getSelectionModel().select(newNode); 
相关问题