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

Sta*_*low 12 html javascript jquery jquery-ui jstree

如何在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"))
 });
Run Code Online (Sandbox Code Playgroud)

输出:

Selected node = C

Parent of Selected node = B

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

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

任何有关此事的帮助或指导将不胜感激.

mat*_*mmo 16

parents在jQuery中使用以获取所有父项,li因为所有树项都lijstree,所以请尝试这样:

var parents = data.rslt.obj.parents("li");
Run Code Online (Sandbox Code Playgroud)

对于孩子们children在jQuery中使用,就像这样:

var children = data.rslt.obj.parent().find('li');
Run Code Online (Sandbox Code Playgroud)

编辑使用上面的内容,这里是如何获取所有父级和子级,并将它们放在每个的所有数组中:

父母:

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

儿童:

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


Sta*_*low 11

1更简单的解决方案

 .get_path ( node , id_mode )
Run Code Online (Sandbox Code Playgroud)

将路径返回到节点,可以是ID数组,也可以是节点名数组.mixed node:这可以是指向树中元素的DOM节点,jQuery节点或选择器,我们想要它的路径.bool id_mode:如果设置为true,则返回ID而不是父节点的名称.默认值为false.

// 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);
Run Code Online (Sandbox Code Playgroud)