javascript 用内容初始化 tinymce

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26839614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:34:54  来源:igfitidea点击:

initialize tinymce with content

javascripttinymcetinymce-4

提问by M. Page

I have a page containing one tinymce4 editor instance. I want to initialize this editor with some content, programmatically. I know that I have to call: tinymce.get('editor').setContent('my content');

我有一个包含一个 tinymce4 编辑器实例的页面。我想以编程方式用一些内容初始化这个编辑器。我知道我必须打电话:tinymce.get('editor').setContent('my content');

However I have trouble to do this when tinymce is getting initialized. This question has already been asked: initialize tinyMCE with default contentbut the answer that was given at that time is not working, at least for tinymce4.

但是,当 tinymce 被初始化时,我很难做到这一点。已经有人问过这个问题:用默认内容初始化tinyMCE,但当时给出的答案不起作用,至少对于tinymce4。

Here is what I have tried:

这是我尝试过的:

1st attempt:

第一次尝试:

    tinymce.init({
      mode: "textareas",
      ...
      setup: function (editor) {
         ...
         editor.setContent('my content');
      }
   });

-> Uncaught TypeError: Cannot read property 'body' of undefined

-> 未捕获的类型错误:无法读取未定义的属性“body”

2nd attempt:

第二次尝试:

    tinymce.init({
      mode: "textareas",
      ...
    };
    tinymce.get('editor').setContent('my content');

-> Uncaught TypeError: Cannot read property 'setContent' of null (however if I do this when the page containing the tinymce editor has already been loaded, it works).

-> 未捕获的类型错误:无法读取 null 的属性“setContent”(但是,如果我在包含 tinymce 编辑器的页面已加载时执行此操作,则它可以工作)。

3rd attempt (SO 12083361 answer):

第三次尝试(SO 12083361 答案):

$(document).ready(function(){
    tinymce.get('editor').setContent('my content');
});

-> Uncaught TypeError: Cannot read property 'setContent' of null

-> 未捕获的类型错误:无法读取 null 的属性“setContent”

All this fails with tinymce.activeeditor.setContent('my content');as well.

所有这些都失败了tinymce.activeeditor.setContent('my content');

Where should I place tinymce.get('editor').setContent('my content');in my code to have it working ?

我应该tinymce.get('editor').setContent('my content');在我的代码中的哪个位置放置它才能使其正常工作?

回答by Donatas Bacius

With version 4 you should do it like this:

使用第 4 版,您应该这样做:

tinymce.init({selector:'textarea'});
tinymce.activeEditor.setContent('custom');

Here's a fiddle.

这是一个小提琴

回答by Jeppe Andreasen

I've used the init_instance_callback, which is fired when the editor is ready to setContent.

我使用了 init_instance_callback,它在编辑器准备好 setContent 时触发。

var options = { ... };
options.init_instance_callback = function (editor) {
    editor.setContent(initialContent);
};
$("some-selector").tinymce(options);