簡體   English   中英

jstree:通過名稱屬性而不是 id 在 jstree 中選擇一個節點

[英]jstree: Select a node in jstree by name attribute rather than id

我需要通過它的屬性名稱在 jstree 中選擇一個節點。 然后在選擇該節點后,我需要獲取它的 id。 基本上我想根據節點的名稱獲取節點的 id。

我嘗試了以下代碼:

$("#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)

})

非常歡迎您的幫助。 非常感謝

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

至於問題 - 不幸的是,這行不通,因為 jstree 只在 DOM 中保留可見節點,這意味着如果您的 LI 節點未顯示(例如,如果其父節點已關閉),您將無法在 DOM 中找到它.

我不確定 LI 節點上的 name 屬性是否有效,但無論如何 - 如果您堅持以這種方式查找節點,則必須遍歷內部 jstree 模型。 這是你的方法: http : //jsfiddle.net/DGAF4/450/

這是我從 vakata 的小提琴中編寫的一個函數。 將“MyAttribute”設置為您的屬性。 將 'MyAttribute's Value 傳遞給函數,它將按屬性選擇您的 JSTree 節點。

//SELECT JSTREE by Attribute 
function selectNodeByMyAttribute (AttrValue) {
    $("#jstree").jstree().deselect_all(true);

    var instance = $("#jstree").jstree(true);
    var m = instance._model.data;
    for (var i in m) {
        if (m.hasOwnProperty(i) && i !== '#' && m[i].li_attr.MyAttribute && m[i].li_attr.MyAttribute === AttrValue) {
            instance.select_node(i);
            break;
        }
    }
}

我認為它會有所幫助

<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/

您可以獲得所有節點的平面數組,並在不遞歸的情況下搜索名稱以獲取節點的 id。 此代碼將為您提供具有搜索名稱的節點的最后一次出現。

var m = $("#tree1").jstree(true).get_json('#', {flat:true});
for(var i in m) {
      if(m[i].text === isa_name ) {
        myId =  m[i].id;
      }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM