2012-04-09 69 views
2

我想在现有节点内部或下面创建一个节点,具体取决于它是否是根节点。 (树小部件通常是树或树的列表,没有可见的根节点。)如何将节点标识为根节点?

我试过get_parent,但是我怎么知道这是否是根节点?

var parent = $("#demo1").jstree('_get_parent', $("#foo")); 
var node = $("#demo1").jstree('_get_node', $("#foo")); 

让我困惑的是,get_node似乎返回与get_parent相同的对象。

我正在使用jstree_pre1.0_fix_1。

编辑:

我结束了检查父的父的著名ID。

var node = $(e.replyto); 
if (node.length) { 
    if (node.parent().parent().attr('id') == 'demo1') { 
    $("#demo1").jstree("create_node", node, 'last',{'attr': {'id':e.id}, 'state':'open', 'data': e.data}) ; 
    } else { 
    $("#demo1").jstree("create_node", node, 'after',{'attr': {'id':e.id}, 'state':'open', 'data': e.data}) ; 
    } 
} else { 
    $("#demo1").jstree("create_node", -1, 'after',{'attr': {'id':e.id}, 'state':'open', 'data': e.data}); 
} 
+0

在大多数实现中,根节点的父节点是“null”或其本身。也许,情况就是这样。 – kirilloid 2012-04-09 06:36:59

+0

定义“顶级节点”。 – RobG 2012-04-09 09:14:12

+0

我编辑了问题,并用根节点替换顶级节点并试图定义它。 – 2012-04-09 09:27:16

回答

3

您可以在节点上调用get_parent()。如果它返回'#',那么该节点是一个根节点。 E.G:

var node = ...; 

if($('#demo1').jstree(true).get_parent(node) == '#') { 
    // node is a root node 
} 
2

这不是理想的解决方案,但你可以在参数使用_get_children-1得到所有根节点和测试,如果您的节点是在列表中。

._get_children (node) 
    Use -1 to return all root nodes. 

(从http://www.jstree.com/documentation/core

+0

谢谢。开始使用的好解决方案。如果对每个插入进行线性搜索的速度太慢,我可以在插入根节点时使用额外的属性来标记它们。 – 2012-04-09 08:28:02

+0

您也可以使用'get_container_ul()'检索容器并使用jQuery函数[.contains()](http://api.jquery.com/jQuery.contains/) – 2012-04-09 09:04:58

1

我一直在挣扎了一下这一点,因为我试图使用上下文菜单插件。我不希望用户能够创建新的根节点。我只想让他们创建子节点。 (根节点代表当前用户所属的组,由管理员预先设置)。我的第一个混淆是,_get_children返回一个对象具有length属性。它不是一个数组,但它具有与实际根节点数量正确对应的length属性。查看底层代码,jstree_get_children方法使用jQuery的children方法,该方法返回索引为0,1,2等的子节点以及其他jQuery属性和方法。我发现仅提取节点阵列并使用indexOf检查当前节点是否为根节点很方便。所以,这里是从我的jstree上下文菜单配置的items财产片段:

'items': function(node){ 
    var rootChildren = this._get_children(-1), 
    rootNodes = [], 
    i; 
    //rootChildren is now a fancy jQuery object with the child nodes assigned 
    //to keys 0, 1 etc. 
    //Now create a simple array 
    for(i = 0; i < rootChildren.length; i += 1){ 
     rootNodes[i] = rootChildren[i]; 
    } 
    //We can now use indexOf to check if the current node is in that array 
    //Note again that node is a fancy jQuery object, the actual DOM element 
    //is stored in node[0] 
    console.log(rootNodes.indexOf(node[0]) > -1); 
    //code here to add whatever items you want to the context menu. 
} 

如果你右击在你的树,你会看到true为根节点的控制台窗口和false任何节点更低下层。请注意,对于IE低于8(我认为),您需要为Array提供indexOf方法,因为早期版本的IE不提供indexOf作为本地方法。

相关问题