首次使用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" ] });
关键改动说明
- 合并plugins配置:移除开头重复的
plugins: ["contextmenu"],仅保留包含全部插件的配置项,避免配置覆盖。 - 获取jsTree实例:在
items函数内通过$('#jstreeContent').jstree(true)获取已初始化的jsTree实例,确保能调用官方API方法。 - 修正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
相关产品推荐
相关产品推荐

