David的回复似乎很好和高效。我发现了另一种解决方案的变化,您可以使用a_attr属性来区分不同的节点,并基于此生成不同的上下文菜单。
在下面的示例中,我使用了两种类型的节点Folder和Files。我还使用了不同的图标,使用glyphicon。对于文件类型节点,您只能获取重命名和删除上下文菜单。对于文件夹,所有选项都在那里,创建文件,创建文件夹,重命名,删除。
有关完整的代码片段,您可以查看
https://everyething.com/Example-of-jsTree-with-different-context-menu-for-different-node-type
$('#SimpleJSTree').jstree({
"core": {
"check_callback": true,
'data': jsondata
},
"plugins": ["contextmenu"],
"contextmenu": {
"items": function ($node) {
var tree = $("#SimpleJSTree").jstree(true);
if($node.a_attr.type === 'file')
return getFileContextMenu($node, tree);
else
return getFolderContextMenu($node, tree);
}
}
});
初始的JSON数据如下,其中节点类型在a_attr中指定。
var jsondata = [
{ "id": "ajson1", "parent": "#", "text": "Simple root node", icon: 'glyphicon glyphicon-folder-open', "a_attr": {type:'folder'} },
{ "id": "ajson2", "parent": "#", "text": "Root node 2", icon: 'glyphicon glyphicon-folder-open', "a_attr": {type:'folder'} },
{ "id": "ajson3", "parent": "ajson2", "text": "Child 1", icon: 'glyphicon glyphicon-folder-open', "a_attr": {type:'folder'} },
{ "id": "ajson4", "parent": "ajson2", "text": "Child 2", icon: 'glyphicon glyphicon-folder-open', "a_attr": {type:'folder'} },
];
作为上下文菜单项的一部分,创建文件和文件夹可以使用类似下面的代码,作为文件操作。
action: function (obj) {
$node = tree.create_node($node, { text: 'New File', icon: 'glyphicon glyphicon-file', a_attr:{type:'file'} });
tree.deselect_all();
tree.select_node($node);
}
作为文件夹操作:
action: function (obj) {
$node = tree.create_node($node, { text: 'New Folder', icon:'glyphicon glyphicon-folder-open', a_attr:{type:'folder'} });
tree.deselect_all();
tree.select_node($node);
}
var items
移到函数外部,这样它只会被创建一次,并从函数中返回一些项目的选择,例如return {renameItem: items.renameItem};
或return {renameItem: items.renameItem, deleteItem: items.deleteItem};
。 - David Tangif ($(node).hasClass("folder"))
无效。但是这个有效:if (node.children.length > 0) { items.deleteItem._disabled = true; }
- Ryan Vetteseaction: function () {...}
中?如果你想要使用“正常”的功能和菜单项,但只是删除其中一个(例如删除 Delete 但保留 Rename 和 Create),该怎么办?在我看来,这才是 OP 实际上所问的。如果你删除了 Delete 这样的另一个项目,肯定不需要重新编写 Rename 和 Create 的功能吧? - Andy