簡體   English   中英

無法獲取CKEditor的實例

[英]Cannot get instance of CKEditor

我有幾個字段需要用CKEditor初始化,為此我創建了一個包含initEditor方法的輔助類。

下面的方法應該返回初始化的編輯器,但它不會:

window.CKEditorHelper = window.CKEditorHelper || {};

(function (exports) {

    exports.initEditor = function (input, myEditor) {
        ClassicEditor
            .create(document.querySelector(input), {
                language: {
                    ui: 'en'
                    content: 'en'
                }
            })
            .then(editor => {
                myEditor = editor;
            });
    };

})(window.CKEditorHelper);

這是通過以下方式調用的:

let editor = null;
CKEditorHelper.initEditor('#description', editor);

所以當我點擊一個按鈕時:

$('#save').on('click', function(){
    console.log(editor.getData());
});

我明白了:

無法讀取null的屬性'getData'

我做錯了什么?

您的代碼存在一些問題

讓editor = null;

let關鍵字只在函數范圍內定義一個變量,當你在另一個范圍上使用編輯器 (你的點擊句柄事件)時,它可能是未定義的

另一條線

myEditor =編輯;

這簡單地使得對原始編輯器對象的引用將消失

這是我解決它的解決方案

改變你如初始編輯器的方式

window.editorInstance = {editor: null};
CKEditorHelper.initEditor('#description', editorInstance);

將您的CKEditorHelper更改為

window.CKEditorHelper = window.CKEditorHelper || {};

(function (exports) {

exports.initEditor = function (input, myEditorInstance) {
    ClassicEditor
        .create(document.querySelector(input), {
            language: {
                ui: 'en'
                content: 'en'
            }
        })
        .then(editor => {
            myEditorInstance.editor = editor;
        });
};

})(window.CKEditorHelper);

當你想使用你的編輯器時

console.log(editorInstance.editor.getData());

你可以用javascript來表達

$(document).ready(function () {
  CKEDITOR.replace('tmpcontent', { height: '100px' })
})

通過使用以下來獲取價值

$('#save').on('click', function(){
 var textareaValue = CKEDITOR.instances.tmpcontent.getData();
});
<label class="control-label">Message</label>
<textarea name="tmpcontent" id="tmpcontent" class="form-control"></textarea>

//或者是最新版本

var myEditor;

ClassicEditor
    .create( document.querySelector( '#description' ) )
    .then( editor => {
        console.log( 'Editor was initialized', editor );
        myEditor = editor;
    } )
    .catch( err => {
        console.error( err.stack );
    } );

然后使用獲取數據

myEditor.getData();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM