You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Toast UI Editor多实例场景下获取HTML内容报错求助

解决Toast UI多编辑器实例调用方法报错问题

你的问题核心在于没有正确获取到编辑器的实例对象,直接对字符串调用方法必然报错。以下是两种可行的解决方案:

方案1:全局存储编辑器实例(推荐)

修改编辑器初始化代码,将每个实例存入全局对象,后续直接通过ID索引获取:

修改初始化脚本

<div class="textarea-editor" data-name="{{ fieldname }}" data-editorid="editor{{ field.unique_id }}" id="editor-{{field.unique_id}}"></div>

<script>
// 全局对象存储所有编辑器实例,避免变量污染且方便访问
window.toastEditors = window.toastEditors || {};

const EditorConstructor = toastui.Editor;
const editorInstance = new EditorConstructor({
    el: document.querySelector('#editor-{{ field.unique_id }}'),
    height: '200px',
    initialEditType: 'wysiwyg',
    previewStyle: 'vertical',
    toolbarItems: [
        ['heading', 'bold', 'italic', 'strike'],
        ['hr', 'quote'],
        ['ul', 'ol', 'task', 'indent', 'outdent'],
        ['table', 'image', 'link'],
        ['code', 'codeblock'],
        ['scrollSync'],
    ],
    initialValue: `{{ field.value|safe }}`,
});

// 用data-editorid的值作为键,存入全局对象
window.toastEditors['editor{{ field.unique_id }}'] = editorInstance;
</script>

获取内容的代码

$('.textarea-editor').each(function () {
    const editorId = $(this).attr('data-editorid');
    const editor = window.toastEditors[editorId];
    
    if (editor) {
        // 获取HTML内容
        const htmlContent = editor.getHtml();
        // 获取Markdown内容(如果需要)
        const markdownContent = editor.getMarkdown();
        
        // 这里执行存入数据库的逻辑
        console.log(htmlContent);
    }
});

方案2:通过DOM元素直接获取实例

利用Toast UI Editor内置的getInstance方法,传入编辑器绑定的DOM元素即可获取实例:

$('.textarea-editor').each(function () {
    // 当前遍历的DOM元素就是编辑器绑定的容器
    const editor = toastui.Editor.getInstance(this);
    
    if (editor) {
        const htmlContent = editor.getHtml();
        // 执行存入数据库逻辑
        console.log(htmlContent);
    }
});

为什么你的原代码无效?

你之前的代码中,Uieditor是从data-editorid获取的字符串(比如"editor123"),并非编辑器实例对象,也不是DOM元素。直接对字符串调用toastui.getInstance()完全不符合API要求,自然会报错。

内容的提问来源于stack exchange,提问作者kkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 08:56:13