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

调用editor.blocks.insert为EditorJS手动添加新块时出现报错如何解决

你遇到的报错是因为editor.blocks.insert()方法的传参方式不符合API规范,和CDN引入方式没有直接关系,具体排查和解决方法如下:

1. 核心错误原因

EditorJS v2.x版本的blocks.insert()方法参数要求为:第一个参数是块类型字符串,第二个参数是块数据对象,后续可选参数为插入位置、是否聚焦等。你直接将包含type和data的完整块对象作为第一个参数传入,导致EditorJS无法识别对应的块工具,触发属性读取报错。

修正方案:

将插入代码修改为如下形式即可正常运行:

editor.blocks.insert('paragraph', {
  text: 'My header'
});

如果需要批量插入多个块,可以使用editor.blocks.render()方法,直接传入块数组:

const blocksToAdd = [
  {
    type: 'paragraph', 
    data: {
      text: 'My header'
    }
  }
];
editor.blocks.render({ blocks: blocksToAdd });

2. 额外潜在问题

你在EditorJS的onReady回调中初始化了DragDrop插件,但提供的HTML代码中没有引入对应的CDN资源,会导致插件初始化报错,需要在HTML的script引入部分补全:

<script src="https://cdn.jsdelivr.net/npm/editorjs-drag-drop@latest"></script>

3. 优化建议

建议增加EditorJS初始化完成的状态标记,避免用户在编辑器实例未完全就绪时点击按钮触发异常:

let editorReady = false;
const editor = new EditorJS({
  // 其余配置保持不变
  onReady: () => {
    new DragDrop(editor);
    editorReady = true;
  },
});

btn.addEventListener('click', function() {
  if (!editorReady) return;
  editor.blocks.insert('paragraph', {
    text: 'My header'
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:54:03