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

CKEditor 4 setData()偶发失效,instanceReady事件未触发问题排查

CKEditor4 instanceReady事件不触发问题分析与解决

问题原因

当你绑定instanceReady事件时,编辑器可能已经完成初始化(状态为ready),而instanceReady事件仅在编辑器初始化完成时触发一次,后续绑定的回调不会被执行。

开启调试工具时功能正常,是因为调试模式会减慢代码执行速度,此时编辑器还处于unloaded状态,绑定事件后,编辑器后续完成初始化时会触发回调,所以功能正常。

解决方案

方案1:判断编辑器状态,直接处理或绑定事件

先检查编辑器当前状态,如果已经就绪就直接调用setData,否则绑定instanceReady事件:

function prepCkEditor() {
  var oFCKeditor = CKEDITOR.instances.EMAIL_DESC_TEMPLATETextBox;
  if (!oFCKeditor) {
    oFCKeditor = CKEDITOR.replace('EMAIL_DESC_TEMPLATETextBox', {
        language: editorlang,
        toolbar: 'helpsi',
        skin: 'moono',
        scayt_autoStartup: CONFIGURAZIONE.enableSpellCheck,
        scayt_sLang: $('#hfUSER_LANGEXTENDED').val().replace('-', '_'),
        scayt_disableOptionsStorage: 'lang'
    });
  }
  return oFCKeditor;
}

var oFCKeditor = prepCkEditor();
if (oFCKeditor) {
   console.log(oFCKeditor.status);
   if (oFCKeditor.status === 'ready') {
      oFCKeditor.setData(template.TemplateBody);
   } else {
      oFCKeditor.on('instanceReady', function () {
         oFCKeditor.setData(template.TemplateBody);
      });
   }
}

方案2:创建编辑器时直接绑定事件(更可靠)

在调用CKEDITOR.replace创建编辑器后立即绑定事件,同时额外判断状态避免遗漏:

function prepCkEditor() {
  var oFCKeditor = CKEDITOR.instances.EMAIL_DESC_TEMPLATETextBox;
  if (!oFCKeditor) {
    oFCKeditor = CKEDITOR.replace('EMAIL_DESC_TEMPLATETextBox', {
        language: editorlang,
        toolbar: 'helpsi',
        skin: 'moono',
        scayt_autoStartup: CONFIGURAZIONE.enableSpellCheck,
        scayt_sLang: $('#hfUSER_LANGEXTENDED').val().replace('-', '_'),
        scayt_disableOptionsStorage: 'lang'
    });
    oFCKeditor.on('instanceReady', function () {
      oFCKeditor.setData(template.TemplateBody);
    });
    // 若此时编辑器已就绪,直接执行设置
    if (oFCKeditor.status === 'ready') {
      oFCKeditor.setData(template.TemplateBody);
    }
  } else {
    // 编辑器已存在,直接更新内容
    oFCKeditor.setData(template.TemplateBody);
  }
}

prepCkEditor();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 20:11:22