Codemirror不能使用变量来获取或设置Value。

问题描述 投票:0回答:1

大家好,我正在使用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;
                });

在这种情况下,editor2总是未定义的编辑器里面的变化函数是codemirror实例,只有当变化方法被触发,因此globaleditor是未定义的,直到改变,这就是我想改变:) 。

javascript jquery codemirror
1个回答
1
投票

我建议将每个textarea用一个独特的id类包装在div中。这样你就可以指定你想让哪个codemirror实例发生变化事件。

使用change,我更喜欢使用 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;
});
© www.soinside.com 2019 - 2024. All rights reserved.