How to get value of CKEditor 5?

前端 未结 3 1137
花落未央
花落未央 2021-01-12 05:13

I want to be able to return the value of the CKEditor textarea, and also write my text inside it.

I used CKEditor 5 CDN. First this my code for the textarea it works

3条回答
  •  无人共我
    2021-01-12 06:01

    I use another way to work with ckEditors.

    First thing is - I don't want to initialize ckEditor in every page where I use Editors.

    Second thing is - Sometimes I need to access to ckEditors by name.

    So, there is my point of view:

    Add to your Layout:

    
    
    

    Use it in your view:

    
    
    
    
    

    A little css:

    .ck-classic {
        display: none;
    }
    
    .ck-classic-min {
        display: none;
    }
    

    Add tiny JS to Layout (better way to add as separated JS file):

    const ckEditorClassicOptions = {
        toolbar: ['heading', '|', 'bold', 'italic', 'bulletedList', 'numberedList', 'blockQuote', 'link', 'insertTable', 'undo', 'redo'],
        heading: {
            options: [
                { model: 'paragraph', title: 'Параграф' },
                //{ model: 'heading1', view: 'h1', title: 'Heading 1' },
                { model: 'heading2', view: 'h2', title: 'Заголовок 2' },
                { model: 'heading3', view: 'h3', title: 'Заголовок 3' },
                { model: 'heading4', view: 'h4', title: 'Заголовок 4' },
                { model: 'heading5', view: 'h5', title: 'Заголовок 5' }
            ]
        }
    };
    
    const ckEditorClassicOptionsMin = {
        toolbar: ['bold', 'italic']
    };
    
    var allCkEditors = [];
    $(document).ready(function() {
        // Initialize All CKEditors
        allCkEditors = [];
    
        var allHtmlElements = document.querySelectorAll('.ck-classic');
        for (var i = 0; i < allHtmlElements.length; ++i) {
            ClassicEditor
                .create(allHtmlElements[i], ckEditorClassicOptions)
                .then(editor => {
                    allCkEditors.push(editor);
                })
                .catch(error => {
                    console.error(error);
                });
        }
    
        allHtmlElements = document.querySelectorAll('.ck-classic-min');
        for (var j = 0; j < allHtmlElements.length; ++j) {
            ClassicEditor
                .create(allHtmlElements[j], ckEditorClassicOptionsMin)
                .then(editor => {
                    allCkEditors.push(editor);
                })
                .catch(error => {
                    console.error(error);
                });
        }
    
    });
    
    function ckEditor(name) {
        for (var i = 0; i < allCkEditors.length; i++) {
            if (allCkEditors[i].sourceElement.id === name) return allCkEditors[i];
        }
    
        return null;
    }
    

    And after that get Data from where you need:

    ckEditor("tbxQuestion").getData()
    

提交回复
热议问题