我如何select jstree 中的根节点?

How do I select the root node in jstree?

我正在尝试根据它是根节点还是子节点之一在我的 jstree 中嵌入一些功能。 从我浏览过的 jstree 文档和其他 Stack Overflow 帖子中,我现在能够正确填充项目,但是我在如何 select [=14] 中的 jstree 根节点上遇到了障碍=] 条件就像下面的片段。将单词 "root" 附加到 select_node 是否正确?请指教。 (我的根项目称为 "root",如果我必须调用 get_parent() 并检查如何将我的根作为参数传递)。任何继续进行的指示将不胜感激。

$(".myjstree").on("select_node.jstree.root", function (e, data){
// do stuff if this is my root node
});

收听 select_node.jstree.root 没有按预期工作,因为它所做的只是为 select_node.jstree 创建一个额外的命名空间(请参阅 事件名称和命名空间 来自 http://api.jquery.com/on/ 的部分了解更多信息)。 select_node.jstree.root 个事件仍会为所有 select_node.jstree 个事件触发。

相反,您可以通过select_node.jstree中的data.selected 属性检查是否选择了根节点。您也可以像这样通过 $('#jstree').jstree(true).get_node('root') 与它互动:

$('#jstree').jstree({
  core: {
    data: [
      {
        id: 'root',
        text: 'Root',
        state: { opened: true },
        children: [
          { id: 'child-node-1', text: 'Child 1' },
          { id: 'child-node-2', text: 'Child 2' }
        ]
      }
    ]
  }
});
$('#jstree').on("changed.jstree", function (e, data) {
  if (data.selected.length === 1 && data.selected[0] === 'root') {
    let root_node = $('#jstree').jstree(true).get_node('root');
    console.log(root_node);
  }
});
@import "https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css";
<div id="jstree"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>