The contextmenu
plugin already has support for this. From the documentation you linked to:
items
: Expects an object or a function, which should return an object. If a function is used it fired in the tree's context and receives one argument - the node that was right clicked.
因此,您可以提供以下函数,而不是让contextmenu
使用硬编码对象.它判断在名为"Folder"的类中单击的元素,并通过从对象中删除"delete"菜单项来删除该菜单项:
function customMenu(node) {
// The default set of all items
var items = {
renameItem: { // The "rename" menu item
label: "Rename",
action: function () {...}
},
deleteItem: { // The "delete" menu item
label: "Delete",
action: function () {...}
}
};
if ($(node).hasClass("folder")) {
// Delete the "delete" menu item
delete items.deleteItem;
}
return items;
}
Note that the above will hide the delete option completely, but the plugin also allows you to show an item while disabling its behaviour, by adding _disabled: true
to the relevant item. In this case you can use items.deleteItem._disabled = true
within the if
statement instead.
应该是显而易见的,但记住使用customMenu
函数初始化插件,而不是使用之前的函数:
$("#tree").jstree({plugins: ["contextmenu"], contextmenu: {items: customMenu}});
// ^
// ___________________________________________________________________|
Edit:如果您不想在每次右键单击时重新创建菜单,可以将逻辑放入"删除"菜单项本身的操作处理程序中.
"label": "Delete",
"action": function (obj) {
if ($(this._get_node(obj)).hasClass("folder") return; // cancel action
}
Edit again: After looking at the jsTree source code, it looks like the contextmenu is being re-created every time it is shown anyway (see the show()
and parse()
functions), so I don't see a problem with my first solution.
However, I do like the notation you are suggesting, with a function as the value for _disabled
. A potential path to explore is to wrap their parse()
function with your own one that evaluates the function at disabled: function () {...}
and stores the result in _disabled
, before calling the original parse()
.
It won't be difficult either to modify their source code directly. Line 2867 of version 1.0-rc1 is the relevant one:
str += "<li class='" + (val._class || "") + (val._disabled ? " jstree-contextmenu-disabled " : "") + "'><ins ";
你可以简单地在这一行前面加一行,判断$.isFunction(val._disabled)
,如果是的话,判断val._disabled = val._disabled()
.然后将其作为补丁提交给创建者:)