问题
I am trying to configure a custom context menu for jsTree. I want files to have two options [Rename, Delete] and I want folders to have one option [Create]
The below code seems correct as described here: Configuring jstree right-click contextmenu for different node types
However this does not seem to work, there are two problems.
- Both context menus display the options [Rename, Delete]
- Choosing either option causes the error: Uncaught TypeError: undefined is not a function

What am I doing wrong? Edit: here is a fiddle
$( document ).ready(function() {
function customMenu(node) {
// The default set of all items
var items = {
createItem: { // The "create" menu item
label: "Create",
action: function () {
this.create(node);
}
},
renameItem: { // The "rename" menu item
label: "Rename",
action: function () {
this.rename(node);
}
},
deleteItem: { // The "delete" menu item
label: "Delete",
action: function () {
this.remove(node);
}
}
};
if ($(node).hasClass("folder") || $(node).hasClass("jstree-closed") || $(node).hasClass("jstree-open")) {
delete items.deleteItem;
delete items.renameItem;
}
else{
delete items.createItem;
}
return items;
}
$('#tree').jstree({
'core': {
'data': [
{ "id": "ajson1", "parent": "#", "text": "Folder 1" },
{ "id": "ajson2", "parent": "ajson1", "text": "File 1" },
{ "id": "ajson3", "parent": "ajson1", "text": "File 2" }
]
},
"plugins": [ "contextmenu" ],
"contextmenu": {items: customMenu}
});
});
回答1:
Okay so the answer is that jstree does not implicitly distinguish between files and folders. If you want to make the distinction you need to add an identifier and custom logic.
To accomplish this I added the following to each of my data objects.
"data" : { "file" : true }
The custom logic then became
if (node.data.file) {
delete items.createItem;
}
else{
delete items.deleteItem;
delete items.renameItem;
}
Furthermore, the manner in which I was implementing custom actions was wrong. I figured this out by looking at the source of jstree (jstree/src/jstree.contextmenu.js). To enable create and delete you must set 'check_callback': true. Then you can for example implement the create action as follows.
createItem: { // The "create" menu item
label: "Create",
action: function (data) {
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference);
inst.create_node(obj, {}, "last", function (new_node) {
new_node.data = {file: true};
setTimeout(function () { inst.edit(new_node); },0);
});
}
},
Full working jsfiddle here.
来源:https://stackoverflow.com/questions/23930052/jstree-custom-contextmenu-not-filtering-based-on-type-folder-file