如何在内容变化时获取ckeditor的内容?

4
我有以下代码用于检测ckeditor表面的更改。
CKEDITOR.instances['editor1'].on("instanceReady", function(){                    
this.document.on("keyup", function(){
console.log("sth changed");
});
});

我希望在编辑器内容变化时获取其内容,以便计算字数。如何使用 CKEDITOR.instances 来实现这一目标?

5个回答

7

检索编辑器内容的唯一正确的方法是:

CKEDITOR.instances.yourInstanceName.getData();

你可以尝试使用 this.on( 'key', function() { ... } );,因为编辑器会触发 key 事件。
此外,我建议你参考 此票 关于 onchange 事件和监测编辑器中的更改。
最后但并非最不重要的是: 已经实现的 wordcount 插件 可以完成你的工作 ;)

4

对于版本5,您可以使用editor.model.document.on('change:data', ...)

类似于:

let someContent = '';

ClassicEditor.create(document.querySelector('#editor')).then(editor => {
  editor.model.document.on('change:data', () => {
    someContent = editor.getData()
  })
}).catch(err => {
  console.log('error loading ckeditor', err);
})

请查看文档:https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/basic-api.html#listening-to-changes。原始回答翻译为“最初的回答”。

1

插件列表中有一个名为@AlfonsoML的“onChange”插件:
onChange

它不仅涵盖了“keyUp”,还包括了更多内容。您可以在他的博客上阅读更多信息,他在博客中描述了捕获的不同事件:
CKEditor的onChange事件


1
尝试这个:

    CKEDITOR.instances["CKEditor"].on('change', function() { 
        console.log(this.getData());
    });

嗨,confile,这个答案出现在审核反馈中,请考虑添加一个简短的描述来解决这个问题。 - Dan Beaulieu

0
你可以使用这个:
<script>   
    CKEDITOR.replace( 'editor1' );
    CKEDITOR.instances.editor1.on("change", function() {
        $("#content-val").html(this.getData())//show content inside #content-val div
    });
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接