You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

首次使用jsTree自定义节点增删改菜单报错:this.create is not a function

解决jsTree自定义右键菜单中“this.create is not a function”错误

问题根源

你的代码里有两个关键问题导致了这个错误:

  • 重复声明plugins配置项,虽不直接触发当前错误,但会造成配置混乱;
  • 右键菜单action函数中的this指向的是菜单选项本身,而非jsTree实例,因此调用this.create会提示方法不存在。

修正后的代码

$('#jstreeContent').jstree({
    "core": {
        "animation": 0,
        "check_callback": true,
        "themes": { "stripes": true },
        'data': equipTree
    },
    "types": {
        "#": {
            "max_children": 1,
            "max_depth": 2,
            "valid_children": ["root"]
        },
        "root": {
            "icon": "/static/3.3.15/assets/images/tree_icon.png",
            "valid_children": ["default"]
        },
        "default": {
            "valid_children": ["default", "file"]
        },
        "file": {
            "icon": "glyphicon glyphicon-file",
            "valid_children": []
        }
    },
    "contextmenu": {
        'select_node': false, 
        items: function ($node) {
            // 获取jsTree实例,这是解决问题的核心
            var tree = $('#jstreeContent').jstree(true);
            return {
                "Create": {
                    "label": "Create a new employee",
                    "action": function () {
                        // 使用实例调用create方法,传入当前节点作为父节点
                        tree.create($node);
                    }
                },
                "Rename": {
                    "label": "Rename an employee",
                    "action": function () {
                        tree.rename($node);
                    }
                },
                "Delete": {
                    "label": "Delete an employee",
                    "action": function () {
                        tree.remove($node);
                    }
                }
            };
        }
    },
    // 合并plugins配置,仅声明一次
    "plugins": [
        "contextmenu", "dnd", "search",
        "state", "types", "wholerow"
    ]
});

关键改动说明

  1. 合并plugins配置:移除开头重复的plugins: ["contextmenu"],仅保留包含全部插件的配置项,避免配置覆盖。
  2. 获取jsTree实例:在items函数内通过$('#jstreeContent').jstree(true)获取已初始化的jsTree实例,确保能调用官方API方法。
  3. 修正action调用逻辑:将this.create(obj)改为tree.create($node),直接用实例调用方法,$node就是当前右键点击的节点对象,无需额外传递。

额外提示

  • core.check_callback必须设为true,否则创建、重命名、删除操作会被jsTree拦截;
  • 若需自定义创建节点的默认行为,可给create方法传入更多参数,比如指定节点类型、初始文本:
    tree.create($node, "last", { text: "New Employee", type: "default" });
    

内容的提问来源于stack exchange,提问作者repmsis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:27:42