[英]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" }
]
}
]
}
});
您可以获得所有节点的平面数组,并在不递归的情况下搜索名称以获取节点的 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.