2015-04-23 19 views
1

我需要通過屬性名稱在jstree中選擇一個節點。然後選擇該節點後,我需要得到它的ID。 基本上我想得到一個節點的id給定它的名字。jstree:通過名稱屬性而不是id來選擇jstree中的一個節點

我嘗試下面的代碼:

$("#tree1").bind("loaded.jstree", function (e, data) { 

var isa_name = "ISA16469"; 

//$("#tree1").jstree("select_node", "#01"); //this code works but it selects by id, I want to select by attribute name 

$("#tree1").jstree("select_node", $("li[name='" + isa_name + "']")); //doesn't work 

var test = $('#tree1').jstree('get_selected').attr('id'); //get id of selected node 
alert(test) 

}) 

你的幫助是最歡迎的。非常感謝

回答

3

當使用ID作爲選擇器(在jstree函數中)時,請不要提供前導#,僅使用ID。

至於這個問題 - 不幸的是,這將無法正常工作,因爲jstree只在DOM中保留可見節點,這意味着如果您的LI節點沒有顯示(例如,如果它的父節點被關閉),您將無法找到它在DOM中。

我不確定在LI節點上具有名稱屬性是否有效,但無論如何 - 如果您堅持以這種方式查找節點,您將不得不遍歷內部jstree模型。這裏是你如何做到這一點: http://jsfiddle.net/DGAF4/450/

0

我認爲這將有助於

<div id="jstree"></div> 

$("#jstree").on('ready.jstree', function() { 
var instance = $("#jstree").jstree(true); 
var branchCont = instance._model.data; 

for(var branchKey in branchCont) { 

    var branch = branchCont[branchKey]; 
    if(branch.text && branch.text === "Child node 1") { 

    instance.select_node(branchKey); 
    break; 
    } 
} 
}); 

$("#jstree").jstree({ 
'core' : { 
    'data' : [ 
     { "text" : "Root node", "children" : [ 
      { "text" : "Child node 1" }, 
      { "text" : "Child node 2" } 
     ] 
     }, 
     { "text" : "Root node2", "children" : [ 
      { "text" : "Child node B1" }, 
      { "text" : "Child node B2" } 
     ] 
     } 
    ] 
} 
}); 

https://jsfiddle.net/shubojs/qj8hty83/3/