【问题标题】:How do I identify a node as being a root node?如何将节点识别为根节点?
【发布时间】:2012-04-09 06:04:42
【问题描述】:

我想在现有节点内部或下方创建一个节点,具体取决于它是否为根节点。 (树部件通常是树的列表或没有可见根节点的树。)

我尝试了 get_parent,但我怎么知道它是否是根节点?

var parent = $("#demo1").jstree('_get_parent', $("#foo"));
var node = $("#demo1").jstree('_get_node', $("#foo"));

令我困惑的是 get_node 似乎返回与 get_parent 相同的对象。

我正在使用 jstree_pre1.0_fix_1。

已编辑:

我最终检查了父母的父母的已知 id。

var node = $(e.replyto);
if (node.length) {
  if (node.parent().parent().attr('id') == 'demo1') {
    $("#demo1").jstree("create_node", node, 'last',{'attr': {'id':e.id}, 'state':'open', 'data': e.data}) ;
  } else {
    $("#demo1").jstree("create_node", node, 'after',{'attr': {'id':e.id}, 'state':'open', 'data': e.data}) ;
  }
} else {
    $("#demo1").jstree("create_node", -1, 'after',{'attr': {'id':e.id}, 'state':'open', 'data': e.data});
}

【问题讨论】:

  • 在大多数实现中,根节点的父节点要么是null,要么是它自己。也许,就是这样。
  • 我编辑了问题并将顶级节点替换为根节点并尝试定义它。

标签: javascript jquery jquery-plugins jstree


【解决方案1】:

您可以在节点上调用get_parent()。如果它返回“#”,则该节点是根节点。例如:

var node = ...;

if($('#demo1').jstree(true).get_parent(node) == '#') {
    // node is a root node
}

【讨论】:

    【解决方案2】:

    这不是理想的解决方案,但您可以在参数中使用_get_children-1 来获取所有根节点并测试您的节点是否在列表中。

    ._get_children ( node )
      Use -1 to return all root nodes.
    

    (来自http://www.jstree.com/documentation/core

    【讨论】:

    • 谢谢。入门的好解决方案。如果对每个插入进行线性搜索太慢,我可以在插入根节点时用额外的属性标记它们。
    • 也可以使用get_container_ul()检索容器,使用jQuery函数.contains()
    【解决方案3】:

    我一直在努力解决这个问题,因为我正在尝试使用上下文菜单插件。我不希望用户能够创建新的根节点。我只想让他们创建子节点。 (根节点代表当前用户所属的组,由管理员预先设置)。我的第一个困惑是_get_children 返回一个具有length 属性的对象。它不是一个数组,但它有一个 length 属性正确对应于实际根节点的数量。查看底层代码,jstree_get_children 方法使用 jQuery 的 children 方法,它返回索引为 0、1、2 等的子节点以及其他 jQuery 属性和方法。我发现只提取节点数组并使用indexOf 检查当前节点是否为根节点很方便。所以,这是我的jstree 上下文菜单配置的items 属性中的一个sn-p:

    'items': function(node){
        var rootChildren = this._get_children(-1), 
        rootNodes = [], 
        i;
        //rootChildren is now a fancy jQuery object with the child nodes assigned
        //to keys 0, 1 etc.
        //Now create a simple array
        for(i = 0; i < rootChildren.length; i += 1){
            rootNodes[i] = rootChildren[i];
        }
        //We can now use indexOf to check if the current node is in that array
        //Note again that node is a fancy jQuery object, the actual DOM element
        //is stored in node[0]
        console.log(rootNodes.indexOf(node[0]) > -1);
        //code here to add whatever items you want to the context menu.
    }
    

    如果您在树周围单击鼠标右键,您将在控制台窗口中看到根节点的true 和层次结构较低的任何节点的false。请注意,对于低于 8 的 IE(我认为),您需要为 Array 提供 indexOf 方法,因为早期版本的 IE 不提供 indexOf 作为本机方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多