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

如何动态设置查询选择器属性,实现多实例tui.Editor编辑器?

这问题我之前也碰到过,多实例组件最容易踩变量冲突和选择器硬编码的坑,给你一套完整的解决方案:

第一步:在Partial视图中统一管理传入的ID

首先在Partial视图的顶部,把传入的ID存成一个局部变量,避免重复写ViewData["id"],还能加个默认值防止空值:

@{
    var editorId = ViewData["id"]?.ToString() ?? "default-markdown-editor";
}

第二步:渲染动态ID的编辑器容器

你原来的容器写法没问题,直接用这个变量就行:

<div id="@editorId"></div>

第三步:动态生成编辑器实例和相关函数

核心是避免全局变量冲突,同时动态指定编辑器的目标容器。我们用传入的ID来命名编辑器变量和保存函数,确保每个实例都是独立的:

<script type="text/javascript">
    // 用ID生成唯一的编辑器变量名,防止多实例互相覆盖
    var editor_@editorId = new tui.Editor({
        el: document.querySelector('#@editorId'),
        previewStyle: 'vertical',
        height: '300px',
        initialEditType: 'wysiwyg'
    });

    // 对应每个实例的保存函数,同样用ID区分
    function saveContent_@editorId(e) {
        var content = editor_@editorId.getValue();
        console.log(`Content from ${@editorId}:`, content);
        e.preventDefault();
    }

    // 如果需要绑定提交按钮,也可以在这里动态关联(示例)
    // 假设你有个对应ID的按钮:<button id="save-@editorId">保存</button>
    // document.getElementById('save-@editorId').addEventListener('click', saveContent_@editorId);
</script>

第四步:主视图调用保持不变

你原来的调用方式完全不用改,传入不同的ID就行:

@Html.Partial("_MarkdownEditor", new { id = "executivesummary" })
@Html.Partial("_MarkdownEditor", new { id = "editorsection" })

这样处理后,两个编辑器实例会分别生成editor_executivesummary和editor_editorsection两个独立的变量,各自绑定到对应的容器,再也不会出现选择器硬编码导致的实例覆盖问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:44:23