jsTree :如何在 jsTree 中获取所选节点的 ID 到根节点

jsTree : How to get IDs of selected nodes to root node in jsTree?

本文关键字:jsTree 节点 ID 根节点 获取      更新时间:2023-09-26

如何在jsTree中获取所选节点的ID到根节点?

假设 C 是选定的节点,那么我怎样才能获得 C 的所有父 ID。

一个

    • C

      +C1

      +C2

以下代码将仅返回直接父 ID:如果我选择了 C,那么我只得到 B

 .bind("select_node.jstree", function (event, data) {  
    //`data.rslt.obj` is the jquery extended node that was clicked          
    alert("Selected node = "+ data.rslt.obj.attr("id"));
    alert("Parent of Selected node = "+ data.inst._get_parent(data.rslt.obj).attr("id"))
 });

输出:

Selected node = C

Parent of Selected node = B

有没有办法获取所有父节点ID,即从选定节点到根节点?

  • 如何在jsTree中获取所选节点的所有子节点?

如能就此事项提供任何帮助或指导,将不胜感激。

在 jQuery 中使用 parents 获取所有父项,按li过滤掉,因为所有树项都在jstreeli,试试这个:

var parents = data.rslt.obj.parents("li");

对于孩子,在jQuery中使用children,如下所示:

var children = data.rslt.obj.parent().find('li');

编辑 使用上述方法,以下是获取所有父项和子项并将它们放入每个父项和子项的所有数组中的方法:

父母:

var parents = [];
data.rslt.obj.parents("li").each(function () {
    parents.push({ id: $(this).attr("id"), description: $(this).children("a").text() });
});

孩子:

var children = [];
data.rslt.obj.find("li").each(function () {
    children.push({ id: $(this).attr("id"), description: $(this).children("a").text() });
});

1 更简单的解决方案

 .get_path ( node , id_mode )

返回节点的路径,可以是 ID 数组还是节点名称数组。混合节点:这可以是DOM节点,jQuery节点或指向树中元素的选择器,我们希望其路径.bool id_mode:如果设置为true,则返回ID而不是父级的名称。默认值为假。

// To get path [ID or Name] from root node to selected node 
var ids = data.inst.get_path('#' + data.rslt.obj.attr('id'),true);
// Returns IDs from root to selected node
var names = data.inst.get_path('#' + data.rslt.obj.attr('id'),false); 
// Returns Name's from root to selected node 
alert("Path [ID or Name] from root node to selected node = ID's = "+ids+" :: Name's = "+names);