CKEditor -当DOM节点被删除时销毁实例

CKEditor - destroy an instance when the DOM node has been deleted

本文关键字:实例 删除 DOM 节点 CKEditor      更新时间:2023-09-26

通过阅读CKEditor文档,我看到他们有一个选项来销毁一个实例与CKEDITOR.instances.instanceName.destroy();。然而,如果DOM已经改变,整个所见即所得DOM结构已被删除,我得到以下错误在Chrome:

Uncaught TypeError: Cannot read property 'document' of null

…在Firefox中:

i.contentWindow is null

有办法解决这个问题吗?

由于我的应用程序的结构方式(通过AJAX加载内容),当元素仍然在页面上时,我不能调用.destroy()

如果需要在AJAX调用后销毁ckeditor对象和DOM中的元素,可以通过为函数调用destroy(true)设置布尔参数来实现。这样它就不会尝试更新DOM:

var editor = CKEDITOR.instances[name];
if (editor) { editor.destroy(true); }
CKEDITOR.replace(name);

我写了2个函数来更好地控制这些东西。请注意,在使用这些函数之前,我已经声明了一个变量,但是还有很多更巧妙的方法,但是这种方法对于我需要它的目的来说已经足够好了(我只使用和需要一个实例):

    if(typeof(editor) == 'undefined')
        var editor=null;
    function ck_delete(editor)
    {
        if(typeof(editor) != 'undefined' && editor!=null)
            editor.destroy();
    }
    function ck_init(ck_inst_name)
    {
        var el_id=document.getElementById(ck_inst_name);
        if(typeof(el_id) != 'undefined' && el_id!=null)
        {
            if(typeof(editor) == 'undefined' || editor==null)
            {
                editor=CKEDITOR.replace( ck_inst_name );
            }
            else
            {
                ck_delete(editor);
                editor=null;
                editor = CKEDITOR.replace( ck_inst_name );
            }
        }
    }

我还检查应该被替换的HTML元素是否存在,这样我就不会得到错误消息。

您可以在http://dev.ckeditor.com/ticket/8226应用其中一个补丁,它将工作。我推荐这个:http://dev.ckeditor.com/attachment/ticket/8226/8226_5.patch

我们在GWT中集成CKEDITOR时遇到了这个问题,在一个弹出式对话框中。当对话框被销毁时,CKEDITOR抛出这个错误-"不能读取属性'document'为null。"解决方案是在关闭对话框之前销毁CKEDITOR。(我们必须扩展GWT ckeditor类来覆盖这个——使用Erik给出的editor.destroy(true)语法——谢谢,Erik!)