简体   繁体   English

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

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

I try to set id4 in 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 textarea is replaced by CodeMirror editor. textarea被 CodeMirror 编辑器取代。 How do I set value to it?我如何为其设置值?

Thanks a lot for the help!非常感谢您的帮助!

The way to do this has changed slightly since the release of 3.0.自 3.0 发布以来,执行此操作的方式略有变化。 It's now something like this:现在是这样的:

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

I like examples.我喜欢例子。 Try this:尝试这个:

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

As you said, the textarea is replaced by Codemirror.正如你所说,textarea被Codemirror取代。 But it is replaced by an element with the class "CodeMirror".但它被一个具有“CodeMirror”类的元素所取代。 You can use querySelector to get the element.您可以使用querySelector来获取元素。 The current CodeMirror instance (and its methods) is attached to this element.当前 CodeMirror 实例(及其方法)附加到此元素。 So you can do:所以你可以这样做:

document.querySelector('.CodeMirror').CodeMirror.setValue('VALUE')

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);

This has worked for my (pretty old) version of CodeMirror:这适用于我的(相当旧的)CodeMirror 版本:

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

editor.setCode('your string');

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM