2012-04-09 44 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作爲本地方法。

相關問題