gpt4 book ai didi

jquery - 为不同节点类型配置jstree右键上下文菜单

转载 作者:IT王子 更新时间:2023-10-29 03:25:47 25 4
gpt4 key购买 nike

我在网上的某个地方看到了一个示例,展示了如何自定义 jstree 的右键单击上下文菜单的外观(使用 contextmenu 插件)。

例如,允许我的用户删除“文档”而不是“文件夹”(通过隐藏文件夹上下文菜单中的“删除”选项)。

现在我找不到那个例子了。谁能指出我正确的方向?官方documentation并没有真正帮助。

编辑:

因为我想要默认的上下文菜单只有一两个小的变化,我宁愿不重新创建整个菜单(当然我会这样做,如果这是唯一的方法)。我想做的是这样的:

"contextmenu" : {
items: {
"ccp" : false,
"create" : {
// The item label
"label" : "Create",
// The function to execute upon a click
"action": function (obj) { this.create(obj); },
"_disabled": function (obj) {
alert("obj=" + obj);
return "default" != obj.attr('rel');
}
}
}
}

但它不起作用 - 创建项目总是被禁用(警报永远不会出现)。

最佳答案

contextmenu 插件已经支持这个。从您链接到的文档中:

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 提供一个硬编码对象,不如提供以下函数。它检查为名为“文件夹”的类单击的元素,并通过从对象中删除它来移除“删除”菜单项:

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;
}

请注意,上面的内容将完全隐藏删除选项,但该插件还允许您通过向相关项目添加 _disabled: true 来显示项目,同时禁用其行为。在这种情况下,您可以在 if 语句中使用 items.deleteItem._disabled = true

应该很明显,但请记住使用 customMenu 函数而不是之前的函数初始化插件:

$("#tree").jstree({plugins: ["contextmenu"], contextmenu: {items: customMenu}});
// ^
// ___________________________________________________________________|

编辑:如果您不希望每次右键单击时都重新创建菜单,您可以将逻辑放在删除菜单项本身的操作处理程序中。

"label": "Delete",
"action": function (obj) {
if ($(this._get_node(obj)).hasClass("folder") return; // cancel action
}

再次编辑:在查看 jsTree 源代码后,看起来上下文菜单每次显示时都会重新创建(请参阅 show()parse() 函数),所以我的第一个解决方案没有问题。

但是,我确实喜欢您建议的表示法,将函数作为 _disabled 的值。一个潜在的探索路径是用你自己的函数包装他们的 parse() 函数,在 disabled: function () {...} 评估函数并存储结果在 _disabled 中,在调用原始 parse() 之前。

直接修改源代码也不难。版本 1.0-rc1 的第 2867 行是相关的:

str += "<li class='" + (val._class || "") + (val._disabled ? " jstree-contextmenu-disabled " : "") + "'><ins ";

您可以简单地在此之前添加一行来检查 $.isFunction(val._disabled),如果是,则 val._disabled = val._disabled() .然后将其作为补丁提交给创作者:)

关于jquery - 为不同节点类型配置jstree右键上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4559543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com