如何使用 Javascript 设置 CodeMirror 编辑器的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8378678/
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-08-24 05:45:33  来源:igfitidea点击:

How can I set the value of a CodeMirror editor using Javascript?

javascripttextareacodemirror

提问by Dmitry

I try to set id4in the following code:

我尝试id4在以下代码中设置:

<div id="id1">
    <div id="id2">
        <div id="id3">
            <textarea id="id4"></textarea>
        </div>
    </div>
</div>

By using this code:

通过使用此代码:

document.getElementById('id4').value = "...";

And this:

和这个:

document.getElementById('id3').getElementsByTagName('textarea')[0].value = "...";

But nothing works.

但没有任何作用。

UPDATED:

更新:

The textareais replaced by CodeMirror editor. How do I set value to it?

textarea被CodeMirror编辑器所取代。我如何为其设置值?

Thanks a lot for the help!

非常感谢您的帮助!

回答by Ken Smith

The way to do this has changed slightly since the release of 3.0. It's now something like this:

自 3.0 发布以来,执行此操作的方式略有变化。现在是这样的:

var textArea = document.getElementById('myScript');
var editor = CodeMirror.fromTextArea(textArea);
editor.getDoc().setValue('var msg = "Hi";');

回答by Mariz Melo

I like examples. Try this:

我喜欢例子。尝试这个:

CodeMirror.fromTextArea(document.getElementById(id), {
        lineNumbers: true
    }).setValue("your code here");

回答by lfender6445

CodeMirror ~4.6.0 you can do this, assuming you have a codemirror object:

CodeMirror ~4.6.0 你可以这样做,假设你有一个 codemirror 对象:

var currentValue = myCodeMirrorObject.cm.getValue();
var str = 'some new value';
myCodeMirrorObject.cm.setValue(str);

回答by Quentin

The code you have should work. The most likely explanation for it failing is that the elements do not exist at the time you run it. If so the solutions are to either:

您拥有的代码应该可以工作。它失败的最可能的解释是元素在您运行它时不存在。如果是这样,解决方案是:

  • Move the JS so it appears after the elements have been created (e.g. to just before </body>)
  • Delay execution of the JS until the elements have been created (e.g. by moving it to a function that you assign as the onloadevent handler)
  • 移动 JS 使其出现在元素创建之后(例如,就在之前</body>
  • 延迟 JS 的执行,直到元素被创建(例如,通过将其移动到您指定为onload事件处理程序的函数)

回答by fcunited

This has worked for my (pretty old) version of CodeMirror:

这适用于我的(相当旧的)CodeMirror 版本:

var editor=CodeMirror.fromTextArea('textarea_id');

editor.setCode('your string');