如何在 jstree 中选择根节点?



我正在尝试根据它是根节点还是子节点之一在我的jstree中嵌入一些功能。 从 jstree 文档和我浏览过的其他堆栈溢出帖子中,我现在能够正确填充项目,但我在如何在"select_node"条件下选择 jstree 的根节点方面遇到了障碍,如以下代码片段所示。将"根"一词附加到select_node是否正确?请指教。(我的根项称为"根",如果我必须调用 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事件触发select_node.jstree.root事件。

相反,您可以通过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>

最新更新