【问题标题】:How to get data from CKEditor 5 instance如何从 CKEditor 5 实例中获取数据
【发布时间】:2018-03-30 16:15:08
【问题描述】:

我知道对于 CKEditor 4,你可以像这样获取 textarea 数据:

var content = CKEDITOR.instances['comment'].getData();

CKEditor 5 是如何做到的?

【问题讨论】:

    标签: ckeditor ckeditor5


    【解决方案1】:

    声明一个全局变量,然后使用 editor.getData()。像这样的:

    var editor;
    ClassicEditor
        .create(document.querySelector('#editor'))
        .then(editor => {
            editor=editor;
        })
        .catch(error => {
            console.error(error);
        });
    

    然后,在您的事件处理程序中,这应该可以工作:

    editor.getData();
    

    【讨论】:

      【解决方案2】:

      您可以在Basic API 指南中找到答案。

      基本上,在 CKEditor 5 中没有单一的全局编辑器存储库(如旧的 CKEDITOR.instances 全局变量)。这意味着您需要保留对您创建的编辑器的引用,并在您想要检索数据时使用该引用:

      ClassicEditor
          .create( document.querySelector( '#editor' ) )
          .then( editor => {
              editor.getData(); // -> '<p>Foo!</p>'
          } )
          .catch( error => {
              console.error( error );
          } );
      

      如果您需要在其他情况下检索数据(谁会在初始化编辑器后立即读取它,对吗?;)),然后将对编辑器的引用保存在应用程序状态的某个共享对象或某个变量中范围:

      let theEditor;
      
      ClassicEditor
          .create( document.querySelector( '#editor' ) )
          .then( editor => {
              theEditor = editor; // Save for later use.
          } )
          .catch( error => {
              console.error( error );
          } );
      
      function getDataFromTheEditor() {
          return theEditor.getData();
      }
      

      查看这个 JSFiddle:https://jsfiddle.net/2h2rq5u2/

      编辑:如果您需要管理多个编辑器实例,请参阅CKEDITOR 5 get editor instances

      【讨论】:

      • 并且使用“var theEditor”将是一个更好的选择,而不是“让 theEditor”防止在多次加载中出现“标识符已被声明”错误
      猜你喜欢
      • 2020-01-29
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      相关资源
      最近更新 更多