首页 > 解决方案 > Codemirror 不能使用变量来获取或设置值

问题描述

大家好,我正在使用 Codemirror 编辑器并在 html textarea 标记内添加了标准代码,然后我在 jQuery 中创建 Codemirror 元素,但是当我想使用 setValue 或 getValue 从外部设置元素值时,由于变量不起作用我将 codemirror 定义为未定义。我发现的唯一解决方法是使用 codemirror 的 change 实例将 codemirror 实例保存到全局变量,但随后出现的问题是如何在创建时触发 change 方法?如果 codemirror 分配的变量不会未定义任何建议,那就更好了?

<textarea name="mediaopt" rows="8" cols="80">/*===== MEDIA OPTIMIZATION =====*/
</textarea>
editor2 = CodeMirror.fromTextArea($('textarea[name="mediaopt"]')[0], {
                         lineNumbers: true,
                         lineWrapping: true,
                         smartIndent: true,
                         mode: "text/css",
                         extraKeys: {"Shift-Space": "autocomplete"},
                         autoCloseBrackets: true,
                         matchBrackets: true,
                         closeTags: true,
                         theme: "monokai",
                 }).on('change', editor => {
                        cssmediaopt = editor.getValue();
                        globaleditor = editor;
                });

在这种情况下,编辑器 2 始终是更改函数内的未定义编辑器是 codemirror 实例,它仅在更改方法被触发后才起作用,因此 globaleditor 是未定义的,直到我想要更改的更改:)

标签: javascriptjquerycodemirror

解决方案


我建议将每个文本区域包装在一个具有唯一 id / 类的 div 中。通过这种方式,您可以指定您希望哪个 codemirror 实例具有更改事件。

keyup在课堂上使用我更喜欢使用的更改.CodeMirror

您可以在编辑器初始化后直接设置变量。

var editor2 = CodeMirror.fromTextArea($('textarea[name="mediaopt"]')[0], {
    lineNumbers: true,
    lineWrapping: true,
    smartIndent: true,
    mode: "text/css",
    extraKeys: {"Shift-Space": "autocomplete"},
    autoCloseBrackets: true,
    matchBrackets: true,
    closeTags: true,
    theme: "monokai",
}
var cssmediaopt = editor.getValue();
var globaleditor = editor;

$(document).on('change', '.Editor_2 .CodeMirror', function() {
    cssmediaopt = editor.getValue();
    globaleditor = editor;
});

推荐阅读